DEV Community

Discussion on: What Did You Learn This Week --May 1?

Collapse
 
waylonwalker profile image
Waylon Walker

This week I learned the power of getattr in python. I am using an API that returns an object that is not subscriptable. Attributes are accessed with .thing for instance. Its really nice that it tab completes, but it makes it really hard to loop through and access 10 items. I learned that you can get to them dynamically with getattr.

The backend library essentially looks like this.

class CantGet:
    def __init__(self, items):
        self.__dict__.update(**items)

It gets instansiated with a dictionary.

cg = CantGet(
  {
    'sales': range(10),
    'production': range(10),
    'inventory': range(10)
    }
  )

You can ask for individual items by dot notation, and tab completion works.

>>> cg.sales
range(0,10)

but it's not subscriptable

>>> cg['sales']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'CantGet' object is not subscriptable

So how do you dynamically access it by a string? The answer is getattr!

>>> getattr(cg, 'sales')
range(0,10)

Python is such a wonderful and hackable language