Getting a list of an object's methods?
Alexander Schmolck
a.schmolck at gmx.net
Sun Jun 22 19:55:30 EDT 2003
Jeremy Yallop <jeremy at jdyallop.freeserve.co.uk> writes:
> Alexander Schmolck wrote:
> >>>> import inspect, operator
> >>>> inspect.getmembers(foo, operator.isCallable)
>
> Unfortunately, this isn't any better than the original idea of using
> dir(),
I think it is, see below.
> since inspect.getmembers is implemented using dir().
True.
> As the OP noted, dir() isn't reliable.
True.
The premises are right, but they don't entail the conclusion. `dir`s behavior
is not guaranteed to be stable, but `inspect.getmembers`'s obviously is [1].
Since `inspect.getmembers` is part of python itself, it can freely use any
behavior guaranteed for *a particular python version* and the fact that it
uses `dir` thus becomes and implementation detail that needs to be of no
concern to anyone except the inspect module's official maintainer -- if `dir`
changes, he or she will need to update `inspect.getmembers`. However:
> For example, 'mro' isn't in int's dir(), although it is (the name of) a
> method of type and in type's __dict__.
Indeed, so this looks like a bug to that should be filed (unless `mro` somehow
doesn't qualify as a 'member' -- I can't see why, but this is something I
leave to the wizards).
If these omissions turn out to be important of the OP's desired application,
then he'll indeed need to consider a further alternative (maybe based upon the
union of `inspect.getmembers` and the `__dict__.keys()`, where the latter are
available).
Anyway, this example highlights a problem I'm getting increasingly concerned
about, namely the erosion of python's metaprogramming capabilities. I don't
think "What methods does this object have?" is a question that only a python
wizard should be able to ask and receive a well-defined answer.
'as
Footnotes:
[1] Otherwise the inspect module would be bascially useless.
More information about the Python-list
mailing list