Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing **kwargs received in a wrapper-function definition, to arguments of an enclosed (i.e. wrapped) function call

Oh dear, I hope I got the title right. :)

How can one pass the **kwargs supplied to a wrapper-function definition, to another (enclosed) function call that it wraps. For example:

def wrapped_func(**kwargs):
   # Do some preparation stuff here.
   func('/path/to/file.csv', comma_separated_key=value_injected_here)
   # Do some other stuff.

So for example, this call:

wrapped_func(error_bad_lines=True, sep=':', skip_footer=0, ...)

Should result in this:

func('/path/to/file.csv', error_bad_lines=True, sep=':', skip_footer=0, ...)

I've tinkered with a variety of approaches over the past couple of hours, but each exposed type-preservation vulnerabilities (for the values). I've not used this particular wrapper pattern before, and was wondering if the community could give some help. Thank you in advance.

like image 794
NYCeyes Avatar asked Apr 13 '16 22:04

NYCeyes


2 Answers

**kwargs is a dict, meaning you can use the double splat (**) to unpack it as a list of keyword arguments. So your wrapper function could be like this:

def wrapped_func(**kwargs):
   # Do some preparation stuff here.
   func('/path/to/file.csv', **kwargs)
   # Do some other stuff.
like image 187
Natecat Avatar answered Oct 09 '22 05:10

Natecat


Why not simply merge the kwargs:

def func(*args, **kwargs):
    print args
    print kwargs


def wrapped_func(**kwargs):
    # Do some preparation stuff here.
    func('/path/to/file.csv', **dict(comma_separated_key='value_injected_here', **kwargs))
    # Do some other stuff.


wrapped_func(error_bad_lines=True, sep=':', skip_footer=0)

# Outputs:
('/path/to/file.csv',)
{'skip_footer': 0, 'error_bad_lines': True, 'comma_separated_key': 'value_injected_here', 'sep': ':'}
like image 37
fips Avatar answered Oct 09 '22 07:10

fips