Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does 1.__add__(1) yield a syntax error?

Tags:

python

Why does

1.__add__(1)

yield SyntaxError: invalid syntax? What do the extra brackets add?

(1).__add__(1)
like image 339
Randomblue Avatar asked Feb 07 '12 13:02

Randomblue


1 Answers

This is an effect of the tokenizer: 1.__add__(1) is split into the tokens "1.", "__add__", "(", "1", and ")", since the tokenizer always tries to built the longest possible token. The first token is a floating point number, directly followed by an identifier, which is meaningless to the parser, so it throws a SyntaxError.

Simply adding a space before the dot will make this work:

>>> 1 .__add__(1)
2
like image 177
Sven Marnach Avatar answered Sep 24 '22 17:09

Sven Marnach