why do we invoke print after importing print_function (in Python 2.6)

前端 未结 6 901
再見小時候
再見小時候 2021-01-01 08:15

To get the 3.0 print function we do the following in Python 2.6:

from __future__ import print_function

But to use the function we invoke pr

6条回答
  •  感情败类
    2021-01-01 09:02

    Minimal example

    >>> print     # Statement.
    
    >>> from __future__ import print_function
    >>> print     # Function object.
    
    >>> print()   # Function call.
    
    >>>
    

    As mentioned at: What is __future__ in Python used for and how/when to use it, and how it works from __future__ are magic statements that alter how Python parses code.

    from __future__ import print_function in particular changes print from a statement into a built-in function, as shown in the interactive shell above.

    Why print(1) works without from __future__ import print_function in Python 2

    Because the:

    print(1)
    

    is parsed as:

    print (1)
    ^^^^^ ^^^
    1     2
    
    1. print statement
    2. argument

    instead of:

    print( 1 )
    ^^^^^^ ^ ^
    1      2 1
    
    1. print() function
    2. argument

    And:

    assert 1 == (1)
    

    as mentioned at: Python tuple trailing comma syntax rule

提交回复
热议问题