Finding the public callables of self

bruno at modulix onurb at xiludom.gro
Thu Feb 9 12:33:18 EST 2006


Sion Arrowsmith wrote:
> Russell Warren <russandheather at gmail.com> wrote:
(snip)
> 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. 
> 
> This last sentence suggests to me something like:
> 
>     attrs = set(s for s in dir(self) if not s.startswith('_'))
>     myCallables = attrs.difference(a.__dict__)
err... s/a.__dict__/self.__dict__/

>     return list(myCallables)


Won't work as expected:

>>> class Tricky(object):
...     class_attrib = 42
...     def __init__(self, attr):
...             self.attr = attr
...     def doit(self):
...             if callable(self.attr):
...                     return self.attr(self)
...
>>> t = Tricky(lambda obj: obj.__class__.__name__)
>>> t
<__main__.Tricky object at 0x2aaaaab28ed0>
>>> def getcallables(obj):
...     attrs = set(s for s in dir(obj) if not s.startswith('_'))
...     callables = attrs.difference(obj.__dict__)
...     return list(callables)
...
>>> getcallables(t)
['doit', 'class_attrib']
>>> t.attr(t)
'Tricky'
>>> t.class_attrib()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: 'int' object is not callable


There are 2 reliable ways to know if an object is callable:
- using callable()
- trying to call it


-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list