4 ms·
> No, it definitionally isn't. The entire point is that `+` is being used to represent operations where `+` makes intuitive sense. Huh? There's no restriction
by mjr00 1y ago
> No, it definitionally isn't. The entire point is that `+` is being used to represent operations where `+` makes intuitive sense.
Huh? There's no restriction in Python's type system that says `+` has to "make sense".
import requests
class Smoothie:
def __init__(self, fruits):
self.fruits = fruits
def __repr__(self):
return " and ".join(self.fruits) + " smoothie"
class Fruit:
def __init__(self, name):
self._name = name
def __add__(self, other):
if isinstance(other, Fruit):
return Smoothie([self._name, other._name])
return requests.get("https://google.com")
if __name__ == "__main__":
print(Fruit("banana") + Fruit("mango"))
print(Fruit("banana") + 123)
> banana and mango smoothie
> <Response [200]>
So we have Fruit + Fruit = Smoothie. Overly cute, but sensible from a CS101 OOP definition and potentially code someone might encounter in the real world, and demonstrates how not all T + T -> T. And we have Fruit + number = requests.Response. Complete nonsense, but totally valid in Python. If you're writing a generic method `slow_add` that needs to support `a + b` for any two types -- yes, you have to support this nonsense.
- pdonis 1y ago> There's no restriction in Python's type system that says `+` has to "make sense". There's no restriction in any language that all code has to make sense. You can write nonsense in any language. Sure, particular types of nonsense might be easier to write in Python than in some other languages, but nonsense is still nonsense. And it's also nonsense to argue that an API designer has to support whatever nonsense a coder can dream up just because it's valid code in that language. The GP post was not talking about algebraic fields or mathematical definitions or what nonsense the language permits, but about API design. The basic issue is that Python's extremely dynamic nature makes some reasonable API designs basically inexpressible. That's just a tradeoff one has to accept when using Python. Every language has tradeoffs.