Search code examples
pythonfunctiondictionaryparameterskeyword-argument

Can I Skip Parameters in Python When Using Kwargs


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.


Solution

  • Don't do this. It makes your code harder to read.

    But if you insist, try modify your globals() scope:

    def func(**kwargs):
        for key, val in kwargs.items():
            globals()[key] = val
        print(globals())
        print(my_var_key)
    
    func(my_var_key='foobar')
    

    and the output is:

    {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x10f058f28>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'test.py', '__cached__': None, 'func': <function func at 0x10ef52268>, 'my_var_key': 'foobar'}
    foobar
    

    This will surely pollute your global namespace (and you cannot use locals() because the interpreter confuses). Again, don't do this.