Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #61536 > unrolled thread

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

Started byJurko Gospodnetić <jurko.gospodnetic@pke.hr>
First post2013-12-11 10:30 +0100
Last post2013-12-11 10:30 +0100
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: Differences between obj.attribute and getattr(obj, "attribute") Jurko Gospodnetić <jurko.gospodnetic@pke.hr> - 2013-12-11 10:30 +0100

#61536 — Re: Differences between obj.attribute and getattr(obj, "attribute")

FromJurko Gospodnetić <jurko.gospodnetic@pke.hr>
Date2013-12-11 10:30 +0100
SubjectRe: Differences between obj.attribute and getattr(obj, "attribute")
Message-ID<mailman.3874.1386754268.18130.python-list@python.org>
   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ć

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web