Skip to content

Instantly share code, notes, and snippets.

@brettcannon
Created August 23, 2020 19:32
Show Gist options
  • Save brettcannon/fec4152857e0ed551b4da515dc63e580 to your computer and use it in GitHub Desktop.
Save brettcannon/fec4152857e0ed551b4da515dc63e580 to your computer and use it in GitHub Desktop.
Demonstration of how **= does not follow the data model appropriately
class PowTest:
def __init__(self, name):
self.name = name
def __ipow__(self, _):
print(f"{self.name}.__ipow__")
return NotImplemented
def __pow__(self, _):
print(f"{self.name}.__pow__")
return NotImplemented
def __rpow__(self, _):
print(f"{self.name}.__rpow__")
return NotImplemented
def __isub__(self, _):
print(f"{self.name}.__isub__")
return NotImplemented
def __sub__(self, _):
print(f"{self.name}.__sub__")
return NotImplemented
def __rsub__(self, _):
print(f"{self.name}.__rsub__")
return NotImplemented
class PowTestSub(PowTest):
pass
A = PowTest("A")
B = PowTestSub("B")
print("Pow binary test ...")
try:
A ** B
except TypeError:
pass
print("Sub binary test ...")
try:
A - B
except TypeError:
pass
print("Pow augment test ...")
A = PowTest("A")
try:
A **= B
except TypeError:
pass
print("Sub augment test ...")
try:
A -= B
except TypeError:
pass
@brettcannon
Copy link
Author

Results:

Pow binary test ...
A.__pow__
B.__rpow__
Sub binary test ...
A.__sub__
B.__rsub__
Pow augment test ...
A.__ipow__
Sub augment test ...
A.__isub__
A.__sub__
B.__rsub__

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment