Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python __add__ magic method with integers

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?

like image 547
Ekrem Dinçel Avatar asked Mar 26 '26 15:03

Ekrem Dinçel


1 Answers

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).

like image 158
Amadan Avatar answered Mar 29 '26 05:03

Amadan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!