[Tutor] Keeping a list of attributes of a certain type

Kent Johnson kent37 at tds.net
Fri Jan 15 22:53:34 CET 2010


On Fri, Jan 15, 2010 at 3:43 PM, Guilherme P. de Freitas
<guilherme at gpfreitas.com> wrote:
> Ok, I checked the answers you all gave me, and the suggestions seem to be 2:
>
> a. Compute the list of members on the fly, with a list comprehension
> that looks up stuff on self.__dict___;
>
> b. Stay with my solution, but substituting the unnecessary "if-else"
> by a simple "if". In sum, maintain a list of members that is updated
> whenever a member is added or removed.
>
> Which one is better? I am new to all this, so please correct me if I
> am wrong. It seems that (a) is better if you do a lot of
> adding/removing members operations compared to the number of lookups
> to the "members" list. Otherwise, (b) is better. Right?

Personally (b) feels more direct and robust. There is no guarantee
that attributes are stored in self.__dict__, they can be in __slots__
or delegated to some other container. For example, here is a class
with no __dict__:

In [1]: class Foo(object):
   ...:     __slots__ = ['bar']
   ...:     def __setattr__(self, name, value):
   ...:         print 'set', name, 'to', value
   ...:         object.__setattr__(self, name, value)

In [2]: f=Foo()

In [3]: f.bar = 'baz'
set bar to baz

In [4]: f.__dict__
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)

C:\Project\(misc)\MangoDB\<ipython console> in <module>()

AttributeError: 'Foo' object has no attribute '__dict__'

Granted if you have control over all the classes this won't happen but
still...relying on __dict__ makes me nervous.

Kent


More information about the Tutor mailing list