Consider the following simplified example:
def f(string, offset=0):
print(string[offset:] if isinstance(offset, int) else string[f.__defaults__[0]:])
f('Hello', 'two')
While the tuple returned by f.__defaults__
gives access to all default argument values in the respective order (i. e. by position), I wonder if there is a way to access them by name/identifier of the argument (here: 'offset'
) from within the function ...
You can use inspect.signature
to obtain the parameters of a given function, from which mapping you can get the default value of a named parameter:
import inspect
def f(string, offset=0):
print(string[offset:] if isinstance(offset, int) else string[f_params['offset'].default:])
f_params = inspect.signature(f).parameters