Margus
Margus

Reputation: 43

How to get information about a function and call it

I want to make a function that detects if a method exists for given instance, what are the parameters that can be passed in and then call the method with proper parameters. I am novice and I have no idea how to do it :(

Upvotes: 2

Views: 245

Answers (4)

Pratik Deoghare
Pratik Deoghare

Reputation: 37172

class Test(object):
    def say_hello(name,msg = "Hello"):
        return name +' '+msg

def foo(obj,method_name):
    import inspect
    # dir gives info about attributes of an object
    if method_name in dir(obj):
        attr_info = eval('inspect.getargspec(obj.%s)'%method_name)
        # here you can implement logic to call the method
        # using attribute information
        return 'Done'
    else:
        return 'Method: %s not found for %s'%(method_name,obj.__str__)

if __name__=='__main__':    
    o1 = Test()
    print(foo(o1,'say_hello'))
    print(foo(o1,'say_bye'))

I think inspect module will be of very much help to you. Main functions used in above code are dir,eval,inspect.getargspec. You can get related help in python docs.

Upvotes: 0

S.Lott
S.Lott

Reputation: 391952

Are you trying to align argument values with a function that has a unknown signature?

How will you match up argument values and parameter variables? Guess?

You'd have to use some kind of name matching.

For example something like this.

someObject.someMethod( thisParam=aValue, thatParam=anotherValue )

Oh. Wait. That's already a first-class part of Python.

But what if the method doesn't exist (for inexplicable reasons).

try:
    someObject.someMethod( thisParam=aValue, thatParam=anotherValue )
except AttributeError:
    method doesn't exist.

Upvotes: 0

Eli Bendersky
Eli Bendersky

Reputation: 273646

Try hasattr

>>> help(hasattr)
Help on built-in function hasattr in module __builtin__:

hasattr(...)
    hasattr(object, name) -> bool

    Return whether the object has an attribute with the given name.
    (This is done by calling getattr(object, name) and catching exceptions.)

For more advanced introspection read about the inspect module.

But first, tell us why you need this. There's a 99% chance that a better way exists...

Upvotes: 3

Andrew Hare
Andrew Hare

Reputation: 351566

Python supports duck typing - simply call the method on the instance.

Upvotes: 1

Related Questions