简体   繁体   中英

How to return a function's arguments from **args

Say I have a function:

def function(arg1, arg2, **args):
    panda = arg.get('panda', None)

How do I find the miscellaneous arguments from **args that weren't processed by the function? For instance if I accidentally passed 'pandas' or 'pand' , how would I find and print pandas / pand?

You need a set of arguments that your function expects (let's say, my_args ). Then you can subtract it from the set of passed arguments. The difference set contains the unexpected arguments:

def foobar(**args):
    my_args = set(['foo','bar','panda']) # Expected arguments
    unknown = set(args) - my_args
    print(unknown) # Or raise an exception

foobar(foo=1,bar=2,foobar=3,pandas="hello!")
# {'pandas','foobar'}

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