exaloop / exaloop/codon

Tuple Type Extensions

Open
#616 1 comment 0 reactions 1 assignee Claimed by @inumanag View on GitHub
bug
Dominant language
Python
Stars
16.8k
Forks
603
Avg merge
4d 23h
Merged PRs (30d)
6

Description

Hi again folks,

Looking for more ways to solve Advent of Code, I found out that at least for Tuples, type extension in the case of addition wants to behave like concatenation, no matter what.

For example:

```py
@extend
class Tuple:
def __add__(self: Tuple[int, int], other: Tuple[int, int]) -> Tuple[int, int]:
print("adding tuples")
return (self[0] + other[0], self[1] + other[1])

def __mul__(self: Tuple[int, int], other: Tuple[int, int]) -> Tuple[int, int]:
print("multiplying tuples")
return (self[0] * other[0], self[1] * other[1])

def rot(self) -> Tuple[int, int]:
x, y = self
return tuple((y, -x))

north = Tuple[int, int](-1, 0)
south = north.rot().rot()

radd = north + south
rmul = north * south

print(radd)
print(rmul)
```

Interestingly ,only the` __mul__` dunder is overloaded:

```
❯ codon run -release bug.py
multiplying tuples
(-1, 0, 1, 0)
(-1, 0)
```

I suppose that is because default `__add__` does exist as a language construct and cannot be overwritten, while the given `__mul__` does not exist between two tuple types.

At this point I would say this is not a bug, and this is actually the way someone would want it, as it would be chaotic otherwise. I admit though it would only be fun for AoC challenges, and maybe nothing else outside of that.

In the same vein, if we try to extend tuples with a method that does not exist in the (Python) language for any type of `other`:

```py
@extend
class Tuple:
def __sub__(self: Tuple[int, int], other: Tuple[int, int]) -> Tuple[int, int]:
print("subtracting tuples")
return (self[0] - other[0], self[1] - other[1])

def rot(self) -> Tuple[int, int]:
x, y = self
return tuple((y, -x))

north = Tuple[int, int](-1, 0)
south = north.rot().rot()

rsub = north - south
print(rsub)
```

Codon says it cannot type check the program:

```
❯ codon run -release bug.py
error: cannot typecheck the program
```

Which I guess I could also see it making sense. But is this the way you would want extensions to behave?

I'm interested in how you see this.

Don't take this as an issue, I don't want to keep you busy with stuff like this =)

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.