object . attribute
I thought 'surely that won't work'. So I went to ipython and did something like this:
In [52]: class MyClass():
....: def __init__(self, attribute):
....: self.attribute = attribute
....:
In [53]: my_object = MyClass(3)
In [54]: my_object.attribute
Out[54]: 3
In [55]: my_object . attribute
Out[55]: 3
In [56]: my_object.attribute == my_object . attribute
Out[56]: True
I wasn't expecting this
In [116]: x . thingie == x.thingie
Out[116]: True
The question is now, is it a pep8 violation my linter misses?
— SaoilĂ (@saoili) June 19, 2015
The ever helpful @brandon_rhodes checked and couldn't see anyplace in pep8 that disallowed it.
@saoili I just scanned PEP-8 and do not see anything stated about whether there need to be spaces around the attribute period or not :)
— Brandon Rhodes (@brandon_rhodes) June 19, 2015
But I recommended that my colleague get rid of it anyway because it looked a bit odd.A few days later I got another reply from @bmispelon
@saoili I thought of your tweet today when I discovered that the following three are not the same:
1.real
1 .real
1..real
— Baptiste Mispelon (@bmispelon) June 24, 2015
I would have expected the first two would return the same thing and the last one would give a syntax error. But in the first and third statements the full stop is interpreted as a floating point operator, so the first one gives a syntax error, the second gives 1, and the last one gives 1.0.
Knowing all that, can you predict which of the following will give syntax errors, and what the others evaluate to? I suggest using the python interpreter or ipython to check your answers. Have fun!
1) 1.real
2) 1 .real
3) 1. real
4) 1 . real
5) 1..real
6) 1 ..real
7) 1.. real
8) 1 .. real
9) 1. .real
10) 1. .real
and
11) 1 . . real
TLDR:
- The full stop in python is both the attribute access operator and the float operator.
- The attribute access operator can have any number of spaces on either side of it.
- The float operator cannot have any spaces on either side of it.
- If there is a full stop immediately after an integer, Python will interpret it as the float operator, even if there are no numbers after it, even if you meant it to be an access operator.