import inspect
def foo(a, b, x='blah'):
pass
print(inspect.signature(foo))
# (a, b, x='blah')
Python 3.5+ recommends inspect.signature().
import inspect
def foo(a, b, x='blah'):
pass
print(inspect.signature(foo))
# (a, b, x='blah')
Python 3.5+ recommends inspect.signature().
Arguably the easiest way to find the signature for a function would be help(function):
>>> def function(arg1, arg2="foo", *args, **kwargs): pass
>>> help(function)
Help on function function in module __main__:
function(arg1, arg2='foo', *args, **kwargs)
Also, in Python 3 a method was added to the inspect module called signature, which is designed to represent the signature of a callable object and its return annotation:
>>> from inspect import signature
>>> def foo(a, *, b:int, **kwargs):
... pass
>>> sig = signature(foo)
>>> str(sig)
'(a, *, b:int, **kwargs)'
>>> str(sig.parameters['b'])
'b:int'
>>> sig.parameters['b'].annotation
<class 'int'>
Getting Function signature in CPython
Using / and * in Python function signatures
Helping people understand function signature syntax - Documentation - Discussions on Python.org
Is there a way to check a function's signature in Python? - Stack Overflow
Videos
Hi everyone,
I've been exploring the use of / and * in Python function signatures to specify positional-only and keyword-only arguments. I understand the syntax, but I'm curious about their practical implications and best practices. I am coding for more than two years now and have never used them myself and i see them really rarely. That's why would like to learn about others experiance and maybe get some advice when it is appropriate to use them in my own functions?
Looking forward to your insights! Thanks!
inspect.getargspec is deprecated in Python 3. Consider something like:
import inspect
len(inspect.signature(foo).parameters)
This will include args and kwargs as one parameter, each.
If you don't want to include args and kwargs, consider:
len(inspect.getfullargspec(foo)[0])
You can use:
import inspect
len(inspect.getargspec(foo_func)[0])
This won't acknowledge variable-length parameters, like:
def foo(a, b, *args, **kwargs):
pass