Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Send unknown parameters to a function not as dictionary

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading