I want to inspect a Tornado coroutine to see if it has certain keywords. Normally I would do this with the inspect
module, and in particular inspect.signature
, which works great. However in Python 2 (I have to support both) signature doesn't exist, so I'm looking for an alternative. The standard inspect.getargspec
doesn't work as desired.
In [1]: import inspect
In [2]: import tornado.gen
In [3]: class Foo(object):
...: def a(self, x, y=None):
...: pass
...:
...: @tornado.gen.coroutine
...: def b(self, x, y=None):
...: pass
...:
In [4]: foo = Foo()
In [5]: inspect.getargspec(foo.a)
Out[5]: ArgSpec(args=['self', 'x', 'y'], varargs=None, keywords=None, defaults=(None,))
In [6]: inspect.getargspec(foo.b)
Out[6]: ArgSpec(args=[], varargs='args', keywords='kwargs', defaults=None)
In [7]: import sys; sys.version_info
Out[7]: sys.version_info(major=2, minor=7, micro=14, releaselevel='final', serial=0)
Is there a way, in Python 2, to answer questions like "does foo.b
have a parameter named y
?"
There is nothing in the Python 2 standard library that can do this (but as you noted on Python 3 it works fine). You'll need to access the __wrapped__
attribute yourself. As suggested in Martijn Pieters' answer to a similar question, you could use a copy of the inspect.unwrap
function from Python 3 or a simplified version like
def unwrap(func):
while hasattr(func, '__wrapped__'):
func = func.__wrapped__
return func