Skip to content

Instantly share code, notes, and snippets.

@mdales
Last active September 8, 2022 15:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mdales/2f284a2c7e75c1f92b039851fb968e5a to your computer and use it in GitHub Desktop.
Save mdales/2f284a2c7e75c1f92b039851fb968e5a to your computer and use it in GitHub Desktop.
Ahhh, fun with introspection
#!/usr/bin/env python3
class Foo:
def __init__(self, lhs, op=None, rhs=None):
self.lhs = lhs
if op: self.op = op
if rhs: self.rhs = rhs
def __str__(self):
try:
return f"({self.lhs} {self.op} {self.rhs})"
except AttributeError:
return str(self.lhs)
def __add__(self, other):
return Foo(self, "__add__", other)
def __sub__(self, other):
return Foo(self, "__sub__", other)
def __mul__(self, other):
return Foo(self, "__mul__", other)
def __truediv__(self, other):
return Foo(self, "__truediv__", other)
def eval(self):
try:
return getattr(self.lhs.eval(), self.op)(self.rhs.eval())
except AttributeError:
return self.lhs
a = Foo(42.0)
b = Foo(7.0)
c = (a + b) / b
print(c)
print(c.eval())
c = a + (b / b)
print(c)
print(c.eval())
@mdales
Copy link
Author

mdales commented Sep 8, 2022

Output is:

$  ./test.py
((42.0 __add__ 7.0) __truediv__ 7.0)
7.0
(42.0 __add__ (7.0 __truediv__ 7.0))
43.0

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