Vincent Chalmel
Vincent Chalmel

Reputation: 652

Get a dictionary of current function parameters

I recently had to use a function conditionally dispatching tasks to other functions, with a lot of mandatory and optional named arguments (e.g. manipulating connection strings, spark connectors configs and so on), and it occurred to me that It would have been really much "cleaner" (or "pythonesque") to have a syntax allowing me to pass every arguments from a function to another similar to this :

def sisterFunction(**kwargs) : # Doing things with a bunch of mandatory and optional args
  <do various things/>

def motherFunction(a,b,**kwargs) : 
  <do various things/>
  sisterFunction(**allArgs)

where allArgs would be a dictionary containing keys a,b, and everything in kwargs. This sounds like something python would be inclined to allow and ease but I can't seem to find something similar to a "super kwargs" implemented. Is there a straightforward way to do this ? Is there an obvious good reason it's not a thing ?

Upvotes: 1

Views: 152

Answers (2)

sanyassh
sanyassh

Reputation: 8520

def sisterFunction(**kwargs):
    pass

def motherFunction(a, b, **kwargs):
    sisterFunction(a=a, b=b, **kwargs)

kwargs in sisterFunction will contain a and b keys with corresponding values.

UPDATE

If you don't want to pass long list of function parameters via a=a, there is some workaround to get allArgs:

def motherFunction(a, b, **kwargs):
    allArgs = locals().copy()
    allArgs.update(allArgs.pop('kwargs', {}))
    sisterFunction(**allArgs)

Upvotes: 1

Ralf
Ralf

Reputation: 16505

I would probably go with just using kwargs

def sisterFunction(**kwargs):
    pass

def motherFunction(**kwargs):
    # use the values directly from 'kwargs'
    print(kwargs['a'])

    # or assign them to local variables for this function
    b = kwargs['b']

    sisterFunction(**kwargs)

This will probably be the option with the least code in your function signatures (the definitions of all the parameters to the function).

A KeyError will be raised if some parameters were not passed to the function and the function tries to use them.

Upvotes: 0

Related Questions