tags:

views:

112

answers:

3

What's the difference (if any) between

model.__dict__['title_en']

and

model.__getattribute__('title_en')

and what's best practice ?

+2  A: 

Best practice? Use getattr.

getattr(model, 'title_en')

You only want __getattr__ or __getattribute__ when you want to override the default attribute fetching mechanism.

ChristopheD
+1  A: 

The first won't work because __dict__ is supposed to be a dictionary, not a function. And the correct way is getattr(model, 'title_en').

Ignacio Vazquez-Abrams
right. I meant to use bracket which works but thanks ofr pointing this out.
PhilGo20
+3  A: 

As others have said, the getattr built-in is the right way to get an attribute (in general you don't access Python special methods directly: you access them through built-ins and operators!).

getattr does a lot more than a lookup in the object's __dict__: it supports properties and other descriptors, attributes inherited from the class and its bases (such as methods), attributes that may be dynamically generated via a __getattr__ method (in the object's class, or, again, one of its bases). Just like direct access model.title_en does, when you know the name at the time you're writing the code (in which case of course you wouldn't use getattr;-). This makes it by far the preferred way of accessing an attribute whose name you "learn" only dynamically!

Alex Martelli