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?
What is getattr() used for in Python? We use the Python setattr() function to assign a value to an object's attribute. There might arise a situation where we might want to fetch the values assigned to the attributes. To provide this functionality, Python getattr() built-in function is used.
Python setattr() function is used to set a value to the object's attribute. It takes three arguments an object, a string, and an arbitrary value, and returns none. It is helpful when we want to add a new attribute to an object and set a value to it.
Python | getattr() method Python getattr() function is used to access the attribute value of an object and also gives an option of executing the default value in case of unavailability of the key.
If the specified attribute does not exist in the class, the setattr() creates a new attribute to an object or class and assigns the specified value to it. The following assigns a new attribute to the class itself. Note that this new attribute can only be attached to the specified object.
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 a str
) in an attribute name makes total sense.
>>> class X(object):
... pass
...
>>> x = X()
>>> setattr(x, 'some attribute', 'foo')
>>> x.__dict__
{'some attribute': 'foo'}
>>> x.__dict__['some attribute']
'foo'
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With