Such code:

1.real 

will lead

  File "<stdin>", line 1 1.real ^ SyntaxError: invalid syntax 

But such code:

 var = 1 var.real int('1').real getattr(1, 'real') 

will work fine


With the line, everything works as expected:

 's'.islower() 

What is the problem? Why can one read attributes of a constant number only through the bones, and not normally?

PS: I could not find any articles / questions about this.

    2 answers 2

    Parsing such an expression,

     1.real 

    the interpreter, having seen a dot after the unit, expects that it is a real number, after which, for no reason at all, the word real comes. A syntax error occurs.

    For example, in the following expressions there is no duality, and no error occurs:

     1..real // 1.0 1.0.real // 1.0 1 .real // 1 (1).real // 1 

    A source

      Just add a space:

       >>> 1 .real 1 

      The variant with a space is recognized as a reference to the attribute of an integer:

       $ python -m tokenize -e <<<'1 .real' 1,0-1,1: NUMBER '1' 1,2-1,3: DOT '.' 1,3-1,7: NAME 'real' 1,7-1,8: NEWLINE '\n' 2,0-2,0: ENDMARKER '' 

      A variant without a space is recognized as a number, followed immediately by the name:

       $ python -m tokenize -e <<<'1.real' 1,0-1,2: NUMBER '1.' 1,2-1,6: NAME 'real' 1,6-1,7: NEWLINE '\n' 2,0-2,0: ENDMARKER '' 

      The latter is a syntax error in Python:

       >>> import ast >>> ast.parse('1.real') Traceback (most recent call last): ... File "<unknown>", line 1 1.real ^ SyntaxError: invalid syntax 

      There is no error with the space:

       >>> ast.dump(ast.parse('1 .real', 'eval').body[0]) "Expr(value=Attribute(value=Num(n=1), attr='real', ctx=Load()))"