Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't get argspec for Python callables?

I'm playing with Python callable. Basically you can define a python class and implement __call__ method to make the instance of this class callable. e.g.,

class AwesomeFunction(object):
    def __call__(self, a, b):
        return a+b

Module inspect has a function getargspec, which gives you the argument specification of a function. However, it seems I cannot use it on a callable object:

fn = AwesomeFunction()
import inspect
inspect.getargspec(fn)

Unfortunately, I got a TypeError:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.6/inspect.py", line 803, in getargspec
    raise TypeError('arg is not a Python function')
TypeError: arg is not a Python function

I think it's quite unfortunate that you can't treat any callable object as function, unless I'm doing something wrong here?

like image 716
EnToutCas Avatar asked Oct 22 '10 17:10

EnToutCas


People also ask

What is inspect module in Python?

The inspect module helps in checking the objects present in the code that we have written. As Python is an OOP language and all the code that is written is basically an interaction between these objects, hence the inspect module becomes very useful in inspecting certain modules or certain objects.

What is inspect stack?

inspect. stack() returns a list with frame records. In function whoami() : inspect. stack()[1] is the frame record of the function that calls whoami , like foo() and bar() . The fourth element of the frame record ( inspect.


2 Answers

If you need this functionality, it is absolutely trivial to write a wrapper function that will check to see if fn has an attribute __call__ and if it does, pass its __call__ function to getargspec.

like image 65
Adam Crossland Avatar answered Sep 22 '22 07:09

Adam Crossland


If you look at the definition of getargspec in the inspect module code on svn.python.org. You will see that it calls isfunction which itself calls:

isinstance(object, types.FunctionType)

Since, your AwesomeFunction clearly is not an instance of types.FunctionType it fails.

If you want it to work you should try the following:

inspect.getargspec(fn.__call__)
like image 36
Moe Avatar answered Sep 20 '22 07:09

Moe