Python: How can you access an object or dictionary interchangeably?

I am writing a Django view that sometimes gets data from a database, and sometimes from an external API.

When it comes from the database, it is an instance of the Django model. Attributes must be accessible using dot notation.

Based on the API, the data is a dictionary and is accessible through musical notation.

In any case, some processing is done with the data.

I would like to avoid

if from_DB: item.image_url='http://example.com/{0}'.format(item.image_id) else: item['image_url']='http://example.com/{0}'.format(item['image_id']) 

I am trying to find a more elegant, harsh way to do this.

Is there a way to get / set a key that works on dictionaries or objects?

+4
source share
3 answers

You can use the Bunch class , which converts a dictionary into one that accepts dot notation.

+6
source

In JavaScript, they are equivalent (often useful, I mention this in case you don't know how you do web development), but in Python they are different - [items] versus .attributes .

It is easy to write something that allows access through attributes using __getattr__ :

 class AttrDict(dict): def __getattr__(self, attr): return self[attr] def __setattr__(self, attr, value): self[attr] = value 

Then just use it as if you were using a dict (it will take the dict parameter as a parameter since it extends the dict ), but you can do things like item.image_url and this will hover it over item.image_url , get or install.

+6
source

I don’t know what the consequences will be, but I would add a method to the django model, which reads the dictionary in itself, so you can access the data through the model.

+2
source

All Articles