Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to escape keywords in kwargs

Tags:

python

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 wish to use it as below:

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

As you can see, I wish to use a Python keyword as a key value on the kwargs. I know it is a syntax error. I wonder if there is a way to escape it so one can produce a kwargs with value {'global':True}.

I couldn't find anything related to this in the official docs. I was expecting a way to escape them as kwargs keys are of type string.

like image 450
mostruash Avatar asked Nov 19 '25 21:11

mostruash


1 Answers

The only way you can use Python keywords as keyword-argument names is by unpacking a dictionary:

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

Alternatively, rename the argument (to e.g. global_).

like image 124
jonrsharpe Avatar answered Nov 22 '25 10:11

jonrsharpe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!