Search code examples
python-3.xpycharmreturnrepr

How is return statement different in pycharm and python interpreter?


When I run this code in pycharm, I called my object but repr doesn't return anything, and in my python interpreter it returns TypeError: __repr__ returned non-string (type NoneType). Why is that?

class DictionnaireOrdonne:

    liste_clefs = []
    liste_valeurs = []

    def __init__(self, **clefs_valeurs):

        self.clefs_valeurs = clefs_valeurs
        self._dictionnaire = {}

    def __repr__(self):

        return self.clefs_valeurs

    def __getitem__(self, key):

        return self._dictionnaire[key]

    def __setitem__(self, key, value):

        self._dictionnaire[key] = value


test = DictionnaireOrdonne(one=1, two=2)
test

Solution

  • When you enter an expression in the Python REPL, it evaluates the expression and tries to print out the repr() of the result. repr() calls your object's __repr__(), checks that return value is a string and throws the error.

    Outside the REPL (e.g. when you run it in PyCharm) the expression result is simply discarded, repr() is not called so no error is raised.