I have a function that takes in kwargs. I want to use the kwargs parameters by name without having to declare each explicitly as either a parameter or variable. Is there a way to use my_var_key by passing in kwargs without having to specifically define it in the function call, or is the only way to use kwargs[ "my_var_key" ]?
E.g. I want something like
def func(**kwargs):
print(my_var_key)
as opposed to
def func(my_var_key, **kwargs):
print(my_var_key)
or
def func(**kwargs):
print(kwargs[ "my_var_key" ])
I'm okay with it breaking if the key doesn't exist.
No, there's no practical way to get the syntax you want.
One part of Python's design philosophy is that "explicit is better than implicit", so there are not many situations where names will get added to your namespace without your input. If you want my_var_key to be put into your function's namespace when it's passed as an argument, you should just name it in the def statement. If you want it to only be passable as a keyword argument (not a positional one), you can put a * in the argument list:
def func(*, my_var_key): # arg can only be passed as a keyword: func(my_var_key=1)
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With