Output difference between ipython and python
Asked Answered
S

1

7

It was my understanding that python will print the repr of the output, but this is apparently not always the case. For example:

In ipython:

In [1]: type([])
Out[1]: list

In [2]: set([3,1,2])
Out[2]: {1, 2, 3}

In python:

>>> type([])
<type 'list'>
>>> set([3,1,2])
set([1, 2, 3])

What transformation does ipython apply on the output?

Schelling answered 14/1, 2014 at 10:16 Comment(1)
ipython 1.1.0 on python 2.7.5Schelling
J
11

Instead of repr or standard pprint module IPython uses IPython.lib.pretty.RepresentationPrinter.pretty method to print the output.

Module IPython.lib.pretty provides two functions that use RepresentationPrinter.pretty behind the scenes.

IPython.lib.pretty.pretty function returns the string representation of an object:

>>> from IPython.lib.pretty import pretty
>>> pretty(type([]))
'list'

IPython.lib.pretty.pprint function prints the representation of an object:

>>> from IPython.lib.pretty import pprint
>>> pprint(type([]))
list

IPython uses its own pretty printer because the standard Python pprint module "does not allow developers to provide their own pretty print callbacks."

Jestude answered 14/1, 2014 at 10:20 Comment(3)
Is it documented somewhere that IPython.lib.pretty.pretty is indeed the function which is used? I did IPython.lib.pretty.pretty = lambda *args, **kwargs: 'potato' and there was no change in the output within ipython.Schelling
@wim, good catch, I've edited my answer. IPython.lib.pretty.RepresentationPrinter.pretty = lambda *args, **kwargs: sys.stdout.write('12') will print 12 for any input.Jestude
note that this is only the case if the %pprint magic is ON. I have it turned off by default, and get the behavior the OP is seeing at the regular Python prompt.Awful

© 2022 - 2024 — McMap. All rights reserved.