Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

When it comes from the database, it is a Django model instance. Attributes must be accessed with dot notation.

Coming from the API, the data is a dictionary and is accessed through subscript notation.

In either case, some processing is done on the data.

I'd 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'm trying to find a more elegant, DRY way to do this.

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

like image 955
JAL Avatar asked Dec 10 '22 12:12

JAL


1 Answers

You could use a Bunch class, which transforms the dictionary into something that accepts dot notation.

like image 163
Daniel Roseman Avatar answered May 15 '23 03:05

Daniel Roseman