Skip to content

Return NotImplemented for Expr and GenExpr operators to simplify#1182

Open
Zeroto521 wants to merge 34 commits intoscipopt:masterfrom
Zeroto521:expr/notimplemented
Open

Return NotImplemented for Expr and GenExpr operators to simplify#1182
Zeroto521 wants to merge 34 commits intoscipopt:masterfrom
Zeroto521:expr/notimplemented

Conversation

@Zeroto521
Copy link
Copy Markdown
Contributor

Python prefers to use NotImplemented to handle the unknown input types. It's clear.

Here is an example.
A.__add__ can only receive int type. But a + b can work. When Python calls A.__add__(B), it returns NotImplemented. Then Python will call B.__radd__(A). If both of them are NotImplemented, Python will raise a TypeError.

So we use NotImplemented to simplify Expr, GenExpr, and MatrixExpr.

from __future__ import annotations class A: def __init__(self, value: int): self.value = value def __add__(self, other: int) -> int: if not isinstance(other, int): return NotImplemented return self.value + other class B: def __init__(self, value: int): self.value = value def __add__(self, other: A) -> B: if not isinstance(other, A): return NotImplemented return self.value + other.value def __radd__(self, other: A) -> int: if not isinstance(other, A): return NotImplemented return self.value + other.value if __name__ == "__main__": a = A(5) b = B(10) print(a + 3) # print 8 print(a + b) # print 15 print(a + "test") # raises TypeError # Traceback (most recent call last): # File "test.py", line 35, in <module> # print(a + "test") # raises TypeError # ~~^~~~~~~~ # TypeError: unsupported operand type(s) for +: 'A' and 'str'
Loading
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

3 participants