Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'None' is not displayed as I expected in Python interactive mode

Tags:

python

I thought the display in Python interactive mode was always equivalent to print(repr()), but this is not so for None. Is this a language feature or am I missing something? Thank you

>>> None
>>> print(repr(None))
None
>>>
like image 653
Chris_Rands Avatar asked Sep 22 '16 12:09

Chris_Rands


2 Answers

It's a deliberate feature. If the python code that you run evaluates to exactly None then it is not displayed.

This is useful a lot of the time. For example, calling a function with a side effect may be useful, and such functions actually return None but you don't usually want to see the result.

For example, calling print() returns None, but you don't usually want to see it:

>>> print("hello")
hello
>>> y = print("hello")
hello
>>> y
>>> print(y)
None
like image 60
David Jones Avatar answered Nov 07 '22 13:11

David Jones


Yes, this behaviour is intentional.

From the Python docs

7.1. Expression statements

Expression statements are used (mostly interactively) to compute and write a value, or (usually) to call a procedure (a function that returns no meaningful result; in Python, procedures return the value None). Other uses of expression statements are allowed and occasionally useful. The syntax for an expression statement is:

expression_stmt ::=  starred_expression

An expression statement evaluates the expression list (which may be a single expression).

In interactive mode, if the value is not None, it is converted to a string using the built-in repr() function and the resulting string is written to standard output on a line by itself (except if the result is None, so that procedure calls do not cause any output.)

like image 45
PM 2Ring Avatar answered Nov 07 '22 11:11

PM 2Ring