There is a restriction on the syntax of attribute access, in Python (at least in the CPython 2.7.2 implementation):
>>> class C(object): pass
>>> o = C()
>>> o.x = 123 # Works
>>> o.if = 123
o.if = 123
^
SyntaxError: invalid syntax
My question is twofold:
- Is there a fundamental reason why using Python keyword attribute names (as in
o.if = 123
) is forbidden? - Is/where is the above restriction on attribute names documented?
It would make sense to do o.class = …
, in one of my programs, and I am a little disappointed to not be able to do it (o.class_
would work, but it does not look as simple).
PS: The problem is obviously that if
and class
are Python keywords. The question is why using keywords as attribute names would be forbidden (I don't see any ambiguity in the expression o.class = 123
), and whether this is documented.