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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With