Home > Blockchain >  Send unknown parameters to a function not as dictionary
Send unknown parameters to a function not as dictionary

Time:01-09

Sorry if this is dumb. I am looking for a clean way to do this :

addQuery(slop=33,win=2) //here we could have any new arg like xyz="arg"

def addQuery(unknown_arg):
    print(unknown_arg.slop, unknown_arg.win) //will check and print only if slop/win exist in arg list

I could send dic like : addQuery({slop:33,win:2}) and access with dic["slop"] which is ugly.

I want a tuple like solution. (a=1,b=2). I can't list all possible arguments(>20). The argument to this function could be different each call.

CodePudding user response:

Well the solution to the issue you are facing involves 2 key steps.

  • accepting variable amount of keyword arguments (we will use **kwargs here)
  • making dictionary keys accessible as attributes ( attrdict)

Here is a sample snippet that demonstrates how it can be achieved:

from attrdict import AttrDict # 'pip install attrdict' first

def addQuery(**kwargs):  # helps with step #1
    unknown_arg = AttrDict(kwargs) # make the arguments accessible as attributes (like 'unknown_args.arg' instead of 'unknown_args['arg'])
    print(unknown_arg.slop, unknown_arg.win) # will check and print only if slop/win exist in arg list

addQuery(slop=33,win=2)

CodePudding user response:

Assuming "tuple-like solution" means you want a tuple-like set of parameters in the function, you could use **kwargs to get a dictionary of all implicit values passed and then convert that to a list:

func(explicit_arg, **kwargs):
    keys = ['expected', 'caller', 'keywords'] # this is a list of all possible keywords you expect
    params = [kwargs[k] if k in kwargs.keys() else None for k in keys]

Then you can access your implicit parameters by position in params and they'll be None if not passed.

  •  Tags:  
  • Related