Reputation: 1141
When i am tring this:
>>> "a".__add__("b")
'ab'
It is working. But this
>>> 1.__add__(2)
SyntaxError: invalid syntax
is not working. And this is working:
>>> 1 .__add__(2) # notice that space after 1
3
What is going here? Is it about variable naming rules and is python thinks I am trying to create variable when I am not using space?
Upvotes: 2
Views: 513
Reputation: 50864
When you use 1.
the interpreter think you started writing float number (you can see in the IDE (atleast Pycharm) the dot is blue, not white). The space tell it to treat 1.
as a complete number, 1.0
. 1..__add__(2)
will also do the trick.
Upvotes: 2
Reputation: 198324
Python parser is intentionally kept dumb and simple. When it sees 1.
, it thinks you are midway through a floating point number, and 1._
is not a valid number (or more correctly, 1.
is a valid float, and you can't follow a value by _
: "a" __add__("b")
is also an error). Thus, anything that makes it clear that .
is not a part of the number helps: having a space before the dot, as you discovered (since space is not found in numbers, Python abandons the idea of a float and goes with integral syntax). Parentheses would also help: (1).__add__(2)
. Adding another dot does as well: 1..__add__(2)
(here, 1.
is a valid number, then .__add__
does the usual thing).
Upvotes: 4
Reputation: 7063
The python lexical parser tries to interpret an integer followed by a dot as a floating point number. To avoid this ambiguity, you have to add an extra space.
For comparison, the same code works without problem on a double:
>>> 4.23.__add__(2)
6.23
It also works if you put the int in parentheses:
>>> (5).__add__(4)
9
Upvotes: 2