Differences between obj.attribute and getattr(obj, "attribute")

Jurko Gospodnetić jurko.gospodnetic at pke.hr
Wed Dec 11 04:30:53 EST 2013


   Hi.

On 11.12.2013. 9:23, Johannes Schneider wrote:
> can somebody explain me the difference between accessing attributes via
> obj.attribute and getattr(obj, "attribute")?
>
> Is there a special reason or advantage when using getattr?

   You can not use obj.attribute if you have the word 'attribute' as a 
string, e.g. if you read it from a configuration file.

   Also, you can not test whether an object has an attribute when using 
the object.attribute access method without raising/catching an exception 
and then it can be hard to make sure no other code caused the exception.

   But I suppose in most real-life cases both of the suggested access 
methods are equivalent, since most of the time you really do not have 
names of your attributes as strings and are free to simply assume the 
attribute exists.

   One example problem I had recently where I think you have to use 
getattr(): list the names of all global references in the __builtins__ 
module and, a the type of object each of those references points to.

   [Ran into this one by accident as a part of demonstrating to a new 
Python student what names Python recognizes in some module, and what 
names require additional imports.]

   Hope this helps.

   Best regards,
     Jurko Gospodnetić





More information about the Python-list mailing list