11
>>> my_object.name = 'stuff'
>>> my_str = 'name'
>>> my_object[my_str] # won't work because it's not a dictionary :)

How can I access to the fields of my_object defined on my_str ?

1
  • btw, this is totally valid in javascript Commented Jan 14, 2018 at 4:04

4 Answers 4

28
getattr(my_object, my_str)

Or, if you're not sure if the name exists as a key and want to provide a fallback instead of throwing an exception:

getattr(my_object, my_str, "Could not find anything")

More on getattr.

Sign up to request clarification or add additional context in comments.

5 Comments

What is the advantage against myobject.__dict__[my_str] ? better performance ?
Can I fall back on the standard "It's more Pythonic" answer? Also, tapping into the private __ variables comes with its own set of risks. What you're trying to do is what getattr and setattr are for.
Word of warning though - if you use dynamic attribute names you should either use try: or add if hasattr( before using getattr to make sure you're not trying to access something that's not there.
Huh? getattr does not throw an exception if the attribute doesn't exist. It's basically syntactic sugar for if hasattr give me that else give me the default.
To answer my own ignorance down the road that's because I was always passing a third argument for the default, e.g., getattr(my_object, my_str, None).
4

You can provide support for the [] operator for objects of your class by defining a small family of methods - getitem and setitem, principally. See the next few entries in the docs for some others to implement, for full support.

Comments

0
>>> myobject.__dict__[my_str]
'stuff'

4 Comments

Note that this breaks for properties, __slots__ and __getattr__/__getattribute__/__setattr__ overloads - and probably some other things.
Ok thank you for the info. Do you think getattr(my_object, my_str) is better for performance also ?
Performance is your least concern here. If it is, you could rewrite that part (i.e. the whole loop, to avoid many cross-language calls) in C, but you should have solid proof of an unacceptable slowdown before considering such optimizations.
While this code may provide a solution to problem, it is highly recommended that you provide additional context regarding why and/or how this code answers the question. Code only answers typically become useless in the long-run because future viewers experiencing similar problems cannot understand the reasoning behind the solution.
0

You can't do the __dict__-approach in general. What will always work is

getattr(myobject, my_str)

If you want dict-like access, just define a class with an overloaded index-operator.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.