I am calling an API that is returning an AttributeDict
that has a number of attributes, such as to
and from
.
To access these attributes, I am using dot notation. For example, I use object.to
and that works fine.
When I try to use object.from
, I get an error that says SyntaxError: invalid syntax
. I assume this is because from
is a keyword in Python.
If this is the case, is it possible to access from
with a dot? For now, I am using object["from"]
, which is working, but does not match the rest of my code.
The self keyword is used to access the attributes and methods of the class. self just represents an instance of the class.
Reserved words in Python The print was removed from Python 2 keywords and added as a built-in Python function. All the keywords except True, False and None are in lowercase and they must be written as they are. These cannot be used as variable names, function names, or any other identifiers.
While it's possible to use getattr
to access such attributes:
val = getattr(ad, 'from')
this is more cumbersome than the ad['from']
syntax your AttributeDict supports, and does not satisfy your desire for dotted notation.
There is currently no option to access such attributes with dotted notation. Just stick with indexing. It handles reserved names, names with spaces/hyphens/etc. in them, and names that collide with existing methods (assuming a reasonable AttributeDict implementation). Even if you used getattr
, getattr(ad, 'get')
would still probably return the AttributeDict's get
method instead of the value for a 'get'
key.
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