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

后端 未结 4 1816
再見小時候
再見小時候 2020-12-06 13:14

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

相关标签:
4条回答
  • 2020-12-06 13:52

    It's a deliberate feature. If the python code 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
    
    0 讨论(0)
  • 2020-12-06 13:57

    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.)

    0 讨论(0)
  • 2020-12-06 14:08

    None represents the absence of a value, but that absence can be observed. Because it represents something in Python, its __repr__ cannot possibly return nothing; None is not nothing.

    The outcome is deliberate. If for example a function returns None (similar to having no return statement), the return value of a call to such function does not get shown in the console, so for example print(None) does not print None twice, as the function print equally returns None.

    On a side note, print(repr()) will raise a TypeError in Python.

    0 讨论(0)
  • 2020-12-06 14:19

    In Python, a function that does not return anything but is called only for its side effects actually returns None. As such functions are common enough, Python interactive interpreter does not print anything in that case. By extension, it does not print anything when the interactive expression evaluates to None, even if it is not a function call.

    If can be misleading for beginners because you have

    >>> a = 1
    >>> a
    1
    >>>
    

    but

    >>> a = None
    >>> a
    >>>
    

    but is is indeed by design

    0 讨论(0)
提交回复
热议问题