What happens internally when I press Enter?
My motivation for asking, besides plain curiosity, is to figure out what happens when you
from sympy import *
and enter an expression. How does it go from Enter to calling
__sympifyit_wrapper(a,b)
in sympy.core.decorators? (That’s the first place winpdb took me when I tried inspecting an evaluation.) I would guess that there is some built-in eval function that gets called normally, and is overridden when you import sympy?
All right after playing around with it some more I think I’ve got it.. when I first asked the question I didn’t know about operator overloading.
So, what’s going on in this python session?
It turns out there’s nothing special about how the interpreter evaluates the expression; the important thing is that python translates
x + xinto
x.__add__(x)and Symbol inherits from the Basic class, which defines
__add__(self, other)to returnAdd(self, other). (These classes are found in sympy.core.symbol, sympy.core.basic, and sympy.core.add if you want to take a look.)So as Jerub was saying,
Symbol.__add__()has a decorator called_sympifyitwhich basically converts the second argument of a function into a sympy expression before evaluating the function, in the process returning a function called__sympifyit_wrapperwhich is what I saw before.Using objects to define operations is a pretty slick concept; by defining your own operators and string representations you can implement a trivial symbolic algebra system quite easily:
symbolic.py —
Now we can do:
With a bit of refactoring it can easily be extended to handle all basic arithmetic:
With just a bit more tweaking we can get the same behavior as the sympy session from the beginning.. we’ll modify
Addso it returns aMulinstance if its arguments are equal. This is a bit trickier since we have get to it before instance creation; we have to use__new__()instead of__init__():Don’t forget to implement the equality operator for Symbols:
And voila. Anyway, you can think of all kinds of other things to implement, like operator precedence, evaluation with substitution, advanced simplification, differentiation, etc., but I think it’s pretty cool that the basics are so simple.