Python3 int.__sizeof__() produces syntax error

Viewed 151

The following code produces a syntax error. Does anyone know why syntax errors result when using object attributes?

Python 3.7.4 (default, Jul 27 2020, 09:35:23) 
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>1.__sizeof__()
  File "<stdin
    1.__sizeof__()
               ^
SyntaxError: invalid syntax
>>>
1 Answers

The lexer is greedy, so it recognizes 1.__sizeof__() as float literal 1. followed by an identifier __sizeof__, rather than an int literal followed by a . operator.

$ python -m tokenize <<< "1.__sizeof__()"
1,0-1,2:            NUMBER         '1.'
1,2-1,12:           NAME           '__sizeof__'
1,12-1,13:          OP             '('
1,13-1,14:          OP             ')'
1,14-1,15:          NEWLINE        '\n'
2,0-2,0:            ENDMARKER      ''

Use parentheses to override assist the lexer:

>>> (1).__sizeof__()
28
Related