JAL
JAL

Reputation: 21563

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?

Upvotes: 4

Views: 662

Answers (3)

Daniel Roseman
Daniel Roseman

Reputation: 599846

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

Upvotes: 6

Chris Morgan
Chris Morgan

Reputation: 90842

In JavaScript they're equivalent (often useful; I mention it in case you didn't know as you're doing web development), but in Python they're different - [items] versus .attributes.

It's easy to write something which 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 you'd use a dict (it'll accept a dict as a parameter, as it's extending dict), but you can do things like item.image_url and it'll map it to item.image_url, getting or setting.

Upvotes: 6

Ikke
Ikke

Reputation: 101251

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

Upvotes: 2

Related Questions