Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 2/3 compatible way of inspecting method's arguments

In Python 2, to inspect method's arguments, I can use inspect.getargspec.

In Python 3 however, a drop-in replacement was added under the name inspect.getfullargspec, and inspect.getargspec became deprecated.

Is there a way of writing both Python 2 and 3 compatible code that inspects the arguments? I actually only need to find out, at runtime, the number of arguments a method has.

like image 720
Rok Povsic Avatar asked Mar 05 '19 09:03

Rok Povsic


1 Answers

There is a general solution to write Python2/3 compatible imports

try:
    from inspect import getfullargspec as get_args
except ImportError:
    from inspect import getargspec as get_args

def foo(a, *args, **kwargs):
    pass

print(get_args(foo))

# Python 3
# FullArgSpec(args=['a'], varargs='args', varkw='kwargs', defaults=None, kwonlyargs=[], kwonlydefaults=None, annotations={})

# Python 2
# ArgSpec(args=['a'], varargs='args', keywords='kwargs', defaults=None)
like image 191
sanyassh Avatar answered Nov 04 '22 15:11

sanyassh