Why does Pycharm Console do this with my __repr__ method?

147 Views Asked by At
class B:
    def __init__(self):
         print('boo!')
         self.a = []

    def __repr__(self):
         print(len(self.a))
         ret = ''
         for a in self.a:
             ret += str(a)
         return ret

The following is copy pasted from the Pycharm Console using python 3.8.6 and IPython 7.31.0:

>>> b = B()
boo!
0
0
>> b
Out[4]: 0
0
0
0
0
0
0
0
0
0
0
>> 2 + 3
Out[5]: 5
0
0
0
0
0
0
0
0
0
0

This does not happen in python REPL or iPython running in the cmd (see comments).

Why is this happening?

1

There are 1 best solutions below

4
ljmc On

You're only showing and using B in your code, so we'll use just that.

class B:
    def __init__(self):
         print('boo!')
         self.a = []

    def add_a(self, a):
         self.a.append(a)

    def __repr__(self):
         print(len(self.a))
         ret = ''
         for a in self.a:
             ret += str(a)
         return ret

When you run just B() (a call expression), this is the sequence of things that happens (in python and ipython):

  1. create new instance with __new__ (inherited from object)
  2. initialise the instance with __init__, which prints boo! and sets the a attribute to an empty list []
  3. display the instance you've just created with __repr__, which in your case:
  • prints 0, the length of a attribute
  • set a local ret variable to ''
  • iterates through the a attribute which is empty
  • returns returns '' from ret

However, step 3. applies only to running expressions B(), the python interactive shell runs the expression and displays their result.

The b = B() assignment statement should not trigger a "display result" event (and will not in python, IDLE or ipython).