It seems reserved words can not be used as attributes in python:
$ python
Python 3.6.2 |Continuum Analytics, Inc.| (default, Jul 20 2017, 13:51:32)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> class A:
>>> global = 3
File "<stdin>", line 2
global = 3
^
SyntaxError: invalid syntax
This seems sensible, since it is ambiguous: am I using the global
keyword here? Difficult to say.
But this is not sensible imho:
>>> class A: pass
>>> a = A()
>>> a.global = 3
File "<stdin>", line 1
a.global = 3
^
SyntaxError: invalid syntax
>>> a.def = 4
File "<stdin>", line 1
a.def = 4
^
SyntaxError: invalid syntax
>>> a.super = 5
>>> a.abs = 3
>>> a.set = 5
>>> a.False = 5
File "<stdin>", line 1
a.False = 5
^
SyntaxError: invalid syntax
>>> a.break = 5
File "<stdin>", line 1
a.break = 5
^
SyntaxError: invalid syntax
Why this limitation? I am not using the reserved words in isolation, but as a class attribute: there is not ambiguity at all. Why would python care about that?
a.global
does not use any reserved word: this is an attribute which happens to be called the same as a reserved word. The attribute name will never be used in isolation, eliminating any cause of conflict. It will either be used asa.global
or asself.global
. There is no possible confusion with theglobal
keyword at all. I understand that they can not be declared as class attributes, because that requires special syntax support and that's where a conflict arises. But why not as object attributes? – Rosenblumx.for = 3
. Just how reserved your reserved words are is a matter of language design; it's frequently possible to allow keywords as ordinary identifiers in all sorts of specific contexts, but whether it's actually a good idea is another story. – Veldaveledayaml
(orjson
) data to be accessible as regular object attributes (with a nested object hierarchy). The person writing theyaml
(completely python unrelated) is constrained in that case by some python rules. – Rosenblumyaml
orjson
) has to have some defined structure. Anyway, object attributes can have arbitrary names, trysetattr
/getattr
.setattr(a, "global", 42)
is perfectly allowed. – Neddydata['something']['another']
I want to dodata.something.another
– Rosenblum_
prefix or suffix to the parameter, if you really want to use that word. – Vaticinategl0bal
(as has been suggested to me) or ` glbal` (as I am doing at the moment). Not nice. And anyway I wanted to know the reason behind it. I thought there was a technical reason which escaped me, but it seems to be a matter of taste. – Rosenblumyaml
file has to conform to some standard. And even if that standard definesglobal
as an attribute, you can resort togetattr
. – Neddy