Printing without parentheses varying error message using Python 3

后端 未结 4 1144
被撕碎了的回忆
被撕碎了的回忆 2021-02-05 02:22

When I try to use print without parentheses on a simple name in Python 3.4 I get:

>>> print max
Traceback (most recent call last):
  ...
           


        
4条回答
  •  再見小時候
    2021-02-05 03:17

    Maybe I'm not understanding something, but I don't see why Python should point out the error earlier. print is a regular function, that is a variable referencing a function, so these are all valid statements:

    print(10)
    print, max, 2
    str(print)
    print.__doc__
    [print] + ['a', 'b']
    {print: 2}
    

    As I understand it, the parser needs to read the next full token after print (max in this case) in order to determine whether there is a syntax error. It cannot just say "fail if there is no open parenthesis", because there are a number of different tokens that may go after print depending on the current context.

    I don't think there is a case where print may be directly followed by another identifier or a literal, so you could argue that as soon as there is one letter, a number or quotes you should stop, but that would be mixing the parser's and the lexer's job.

提交回复
热议问题