Hooks, aspect-oriented programming, and design by contract

Alex Martelli aleax at aleax.it
Wed Jan 23 13:33:47 EST 2002


Pedro Rodriguez wrote:
        ...
>   but I have a problem when giving an instance :
>   - dir() on a class or a module will give me a list of attributes, and
>     I will be able to filter the 'callables' so that I can do wrap
>   - dir() won't give methods for an instance, but attributes

In Python 2.2, you get the attributes from both instance and class
(callables and non) for classic classes as well as new-kind ones:

>>> class X:
...   def x(self): pass
...
>>> a=X()
>>> dir(a)
['__doc__', '__module__', 'x']


>   What could be the proper idiom so that an instance is dealt properly ?
>   Should I test if an object is a module or a class (new & old kind) to
>   use dir() and use dir(obj.__class__) otherwise ? Seems uggly to me.

If you need to support old versions of Python as well as 2.2 and
following ones, you need to test the version and behave in different
ways.  This also holds for classes... notice:

>>> class Y(X):
...   def y(self): pass
...
>>> dir(Y)
['__doc__', '__module__', 'x', 'y']

In Python 2.2 the dir of a class also gives you the attributes (methods
or data ones) which come through inheritance, in 2.1 and earlier, it
does not.  So, again, if you need to support both old and new versions,
you need to discriminate.  Ugly, yes, but only for the relatively rare
need of doing metaprogramming (introspection etc) on both old and
new versions of Python from the same source-code base.


Alex





More information about the Python-list mailing list