[Tutor] Ask a class for it's methods

Lie Ryan lie.1296 at gmail.com
Sun Dec 14 03:35:35 CET 2008


On Sat, 13 Dec 2008 10:19:34 +0100, Andreas Kostyrka wrote:

> On Sat, Dec 13, 2008 at 08:03:10AM +0000, Lie Ryan wrote:
>> On Sat, 13 Dec 2008 02:59:34 +0100, Andreas Kostyrka wrote:
>> 
>> > On Fri, Dec 12, 2008 at 06:06:35PM -0500, Shrutarshi Basu wrote:
>> >> I have a list containing strings like :
>> >> 
>> >> func1[]
>> >> func2[1,2]
>> >> func3[blah]
>> >> 
>> >> I want to turn them into method calls (with numeric or string
>> >> arguments) on a supplied object. I'm trying to figure out the best
>> >> way to do this. Since these lists could be very big, and the methods
>> >> could be rather complex (mainly graphics manipulation) I would like
>> >> to start by getting a list of the object's methods and make sure
>> >> that all the strings are valid. Is there a way to ask an object for
>> >> a list of it's methods (with argument requirements if possible)?
>> >
>> > Well, there are ways, but they are not reliable by design. Objects
>> > can return dynamically methods.
>> > 
>> > So use something like this:
>> > 
>> > if callable(getattr(obj, "func1")):
>> >     # func1 exists.
>> > 
>> > Guess nowaday with Python3 released, you should not use callable, but
>> > instead test on __call__
>> > 
>> > if hasattr(getattr(obj, "func1"), "__call__"):
>> 
>> or the more pythonic version would just call func() and catch exception
>> if it's not callable:
>> 
>> try:
>>     func1()
>> except TypeError:
>>     print "func1 is not callable"
> 
> But it happens to be wrong :)
> 
> Consider:
> 
> def func1():
>     raise TypeError("except does not care where in the callstack the
>     exception happens!!!")
> 
> Common sources, IMHE, for TypeErrors include
> int(not_a_string_or_number), which raises a TypeError.

Then it's the lower function's fault (i.e. bug) for not handling that 
exception, and if you really need it, it's trivial to check the "kind" of 
TypeError reraising the exception if it's not what we expect.

try:
    func1()
except TypeError, e:
    if not e.message.endswith('object is not callable'): 
        print 'There is something deeply wrong in your func1'
        raise
    print "func1 is not callable"



More information about the Tutor mailing list