Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I access attributes that have the same name as reserved keywords?

Tags:

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.

like image 743
python_crypto_questions Avatar asked Jan 23 '19 21:01

python_crypto_questions


People also ask

Which keyword is used to get access to the attributes and methods of the class in Python?

The self keyword is used to access the attributes and methods of the class. self just represents an instance of the class.

How do you use reserved words in Python?

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.


1 Answers

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.

like image 110
user2357112 supports Monica Avatar answered Oct 11 '22 16:10

user2357112 supports Monica