-1

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.

baltiturg
  • 350
  • 2
  • 9
  • **kwargs - explained here: https://book.pythontips.com/en/latest/args_and_kwargs.html - I would say - duplicate.... – Michał Zaborowski Jan 08 '22 at 17:18
  • thanks, this is nice but still not amazing because I still need to access with kwargs['slop'], not dot. – baltiturg Jan 08 '22 at 17:24
  • Does this answer your question? [Passing a dictionary to a function as keyword parameters](https://stackoverflow.com/questions/334655/passing-a-dictionary-to-a-function-as-keyword-parameters) – Tomerikoo Jan 08 '22 at 18:25
  • @baltiturg please elaborate why do you need that? Besides - you can use comprehension to deal with it... – Michał Zaborowski Jan 09 '22 at 12:21

2 Answers2

0

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)
Tibebes. M
  • 6,940
  • 5
  • 15
  • 36
  • Did you mean to link to [attrdict](https://pypi.org/project/attrdict/)? That's not built-in... A built-in replacement could be [`argparse.Namespace`](https://docs.python.org/3/library/argparse.html#argparse.Namespace) – Tomerikoo Jan 08 '22 at 18:28
  • @Tomerikoo yeah made a typo.. fixed – Tibebes. M Jan 08 '22 at 18:32
-1

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.

shortorian
  • 1,082
  • 1
  • 10
  • 19