When I am in the Python or IPython console, what is called when I am returned an output?

后端 未结 2 1341
萌比男神i
萌比男神i 2020-12-11 17:43

For example,

python
>> x = 1
>> x
1

I\'m curious about what method/function on x is returning 1. I\'m asking beca

2条回答
  •  星月不相逢
    2020-12-11 18:15

    The other answer addresses repr in a vanilla Python REPL, but it neglected to answer about IPython, which works quite differently and has many more features (and complexity) in regards to REPL printing.

    Here's an example discrepancy:

    # vanilla python:
    >>> type([])
    
    
    # in IPython:
    >>> type([])
    list
    

    IPython has a custom pretty printer and public hooks for customizing repr within IPython. One such hook is _repr_pretty_ (single underscores!) and here's a basic example:

    >>> class Widget:
    ...     def __repr__(self):
    ...         "vanilla"
    ...     def _repr_pretty_(self, p, cycle):
    ...         p.text("chocolate, strawberry")
    ...         
    >>> Widget()
    chocolate, strawberry
    

    For more features, see "Integrating your objects with IPython" in the docs, in particular the Rich display section.

提交回复
热议问题