Let’s say I define this class:
class A:
pass
a = A()
Now obviously I can set attributes like so:
a.x = 5
But with setattr, I can give a attributes which contain whitespace in their names.
setattr(a, 'white space', 1)
setattr(a, 'new\nline', None)
dir(a) contains 'white space' and 'new\nline'.
I can’t access these attributes using the . operator, because it raises a SyntaxError:
>>> a.white space
File "<interactive input>", line 1
a.white space
^
SyntaxError: invalid syntax
>>> a.new\nline
File "<interactive input>", line 1
a.new\nline
^
SyntaxError: unexpected character after line continuation character
But I can with getattr:
>>> getattr(a, 'white space')
1
>>> getattr(a, 'new\nline')
None
Is there a reason behind this functionality? If so, what is it?
Should we make use of this, or conform to the standards defined in PEP8?
Object attributes are merely those attributes defined in an object’s
__dict__. If you think of it from that perspective then allowing whitespace (or any other character that can be included in astr) in an attribute name makes total sense.That said, Python’s language syntax cannot allow for whitespace in direct attribute reference as the interpreter won’t know how to property tokenize (parse) the program source. I’d stick to using attribute names that can be accessed via direct attribute reference unless you absolutely need to do otherwise.