Search code examples
pythonread-eval-print-loop

Python terminology- what are the extra REPL outputs called?


Consider the following code:

class Greet:
    def __init__(self, greeting='Hello'):
        print(greeting)

if __name__ == '__main__':
  print('Initializing and assigning')
  greet = Greet('Shalom!')
  print('Only initializing a class')
  Greet()

If I run the script, I get the output:

Initializing and assigning
Shalom!
Only initializing a class
Hello

However, say I'm running the above code in an interactive REPL, the interaction is as follows:

In 1> greet = Greet('Shalom!')
Shalom!
In 2> Greet()
Hello
<__main__.Greet object at 0x7fac80cc84c0>

If you notice, in the second input i.e. Greet(), I get a second line which is I believe repr of the object that results in the evaluation of the input. What is this EXTRA output called? Because it seems to me that it's a quirk of the REPL itself.


Solution

  • Copying the actual answer from the comments above:

    In the interactive shell, any expressions (not assignments) evaluating to a non-None value will be printed. This does not happen in scripts. You are seeing this output in addition to the actual print statements. If you had put instead greet2 = Greet() then you wouldn't have seen this.

    But posting this answer in order to make an additional comment that doesn't fit into the comment format... you probably in any case wouldn't want to have your object perform an action on initialisation -- better to put that into a separate method:

    >>> class Greeter:
    ...     def __init__(self, greeting='Hello'):
    ...         self.greeting = greeting
    ...     def greet(self):
    ...         print(self.greeting)
    ... 
    >>> greeter = Greeter()
    >>> greeter.greet()
    Hello
    

    You do not see any additional line here in any case, because the greet method returns None.