1

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 ...

T139
  • 140
  • 1
  • 6
  • If you are controlling the code here, you can just use the value you set as default: `... else string[0:]` – user2390182 Apr 08 '20 at 15:18
  • @schwobaseggl I think the idea here is to apply the [DRY](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself) principle. Imagine having to search for and modify 10 places in the code where the default value of `offset` is used when later the default value has to change if you hardcoded `0` in each of those places. – blhsing Apr 08 '20 at 15:24
  • @blhsing That makes sense. On a different note: This will be called by other code. Passing a badly typed parameter is not an error I would silence, but rather want to know about so I can fix it. – user2390182 Apr 08 '20 at 15:38

1 Answers1

0

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
blhsing
  • 91,368
  • 6
  • 71
  • 106