__getattr__ question

Ben Cartwright bencvt at gmail.com
Sat Jun 10 01:22:59 EDT 2006


Laszlo Nagy wrote:
> So how can I tell if 'root.item3' COULD BE FOUND IN THE USUAL PLACES, or
> if it is something that was calculated by __getattr__ ?
> Of course technically, this is possible and I could give a horrible
> method that tells this...
> But is there an easy, reliable and thread safe way in the Python
> language to give the answer?

Why are you trying to do this in the first place?  If you need to
distinguish between a "real" attribute and something your code returns,
you shouldn't mix them by defining __getattr__ to begin with.

If, as I suspect, you just want an easy way of accessing child objects
by name, why not rename "__getattr__" in your code to something like
"get"?

Then instead of
  >>> root.item3
Use
  >>> root.get('item3')

Alternately, make self.items an instance of a custom class with
__getattr__ defined.  This way, root's attribute space won't be
cluttered up.
  >>> root.items.item3

Either way is a few more characters to type, but it's far saner than
trying to distinguish between "real" and "fake" attributes.

--Ben




More information about the Python-list mailing list