开发者

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

开发者 https://www.devze.com 2023-01-25 23:17 出处:网络
I\'m writing a Django view that sometimes get开发者_JS百科s data from the database, and sometimes from an external API.

I'm writing a Django view that sometimes get开发者_JS百科s 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?


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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消