简体   繁体   中英

Sympy __repr__ magic - How does it work?

I noticed that after calling init_printing method of sympy, variable's representation have a better visual appealing. I know that is usually done inheriting repr method.

But when I call __repr__ method, result is different. Why?

Before init_printing being called, this is the result:

>>> import sympy as sy
>>> x = sy.Symbol('x')
>>> sy.exp(x)
exp(x)

>> sy.exp(x).__repr__()
'exp(x)'

After init_printing being called, this is the result:

>>> import sympy as sy
>> sy.init_printing()
>>> x = sy.Symbol('x')
>>> sy.exp(x)
 x
e

>> sy.exp(x).__repr__()
'exp(x)'

Why the repr method doesn't return the same as evaluating the representation of the variable?

>>> sy.exp(x).__repr__
<bound method Basic.__repr__ of exp(x)>

That function installs a custom sys.displayhook() function , which is used in the interactive interpreter to echo the result of expressions:

sys.displayhook is called on the result of evaluating an expression entered in an interactive Python session. The display of these values can be customized by assigning another one-argument function to sys.displayhook .

The implementation is found in the sympy.interactive.printing module :

 def _init_python_printing(stringify_func, **settings): """Setup printing in Python interactive session. """ import sys from sympy.core.compatibility import builtins def _displayhook(arg): """Python's pretty-printer display hook. This function was adapted from: http://www.python.org/dev/peps/pep-0217/ """ if arg is not None: builtins._ = None print(stringify_func(arg, **settings)) builtins._ = arg sys.displayhook = _displayhook 

In other words, this has nothing to do with how the objects implement __repr__ .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM