简体   繁体   中英

Can I pass just the keyword name of a keyword argument in a Python wrapper function?

I have had a dig around in the questions and I can't seem to get this working.

Basically I want to pass an optional keyword to "wrapperfunc" so that I get the relative data out from the "load_data" function that it calls. I want the argument to wrapperfunc to specify what method is done on the data.

I am sure this is a case of unpacking the arguments in the correct way?

import numpy as np

def load_data(remove_smallest = None, remove_largest = None):
    data = np.arange(0,100,1)
    if remove_smallest != None:
        data = data[remove_smallest::]
    elif remove_largest != None:
        data = data[0:(100-remove_largest)]
    else:
        data = data
    return print(data)
    

def wrapperfunc(**args):
    val = [10, 20, 30]
    for v in val:
        load_data(args = v)


wrapperfunc(remove_smallest)
wrapperfunc(remove_largest)

**kwargs are just dicts of str: object , so you can have the wrapper take a key name , create a dict out of that, and using that to call the wrapped function:

def wrapperfunc(key):
    val = [10, 20, 30]
    for v in val:
        load_data(**{key: v})


wrapperfunc('remove_smallest')
wrapperfunc('remove_largest')

No, keyword arguments are purely syntactic , though the name and value are collected in a dict if the name does not correspond to a named parameter.

The closest you can do is pass a str value, then pass an unpacked dict to load_data .

def wrapper(arg):
    val = [10, 20, 30]
    for v in val:
        load_data(**{arg: v})

wrapper('remove_smallest')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM