Finding the public callables of self
Kent Johnson
kent at kentsjohnson.com
Thu Feb 9 11:55:53 EST 2006
Russell Warren wrote:
> Is there any better way to get a list of the public callables of self
> other than this?
>
> myCallables = []
> classDir = dir(self)
> for s in classDir:
> attr = self.__getattribute__(s)
> if callable(attr) and (not s.startswith("_")):
> myCallables.append(s) #collect the names (not funcs)
>
> I don't mean a shorter list comprehension or something that just drops
> the line count, but whether or not I need to go at it through dir and
> __getattribute__. This seems a bit convoluted and with python it often
> seems there's something already canned to do stuff like this when I do
> it.
Use getattr(self, s) instead of self.__getattribute__(s).
You could streamline it a bit with a list comprehension:
myCallables = [ s for s in dir(self) if not s.startswith('_') and
callable(getattr(self, s)) ]
At first I thought self.__dict__ would do it, but callable methods
> seem to be excluded so I had to resort to dir, and deal with the
> strings it gives me.
The callables are attributes of the class and its base classes, not of
self. self.__dict__ just contains instance attributes.
Kent
More information about the Python-list
mailing list