Is there a way to avoid keywords in kwargs

I have the following instance function

class MyClass:

    def __init__(self):
        self.request = dict()

    def my_func(self, **kwargs):
        self.request['arguments'] = kwargs

      

And I want to use it like below:

obj = MyClass()
obj.my_func(global = True)

      

As you can see, I want to use the Python keyword as a key value in kwargs

. I know this is a syntax error. I wonder if there is a way to avoid this so that it can be created kwargs

with a value {'global':True}

.

I couldn't find anything like this in the official docs. I was expecting a way to avoid them since the keys kwargs

are of type string

.

+3


source to share


1 answer


The only way to use Python keywords as keyword names is to unpack the dictionary:

instance.my_func(**{'global': True})

      



Alternatively, rename the argument (for example global_

).

+5


source







All Articles