I know it's a common case for people to give a function an arbitrary number of kwargs with **kwargs
, and then access them as a dictionary; however, I want to explicitly specify my functions kwargs, but still be able to access them as a dictionary.
This is because I want my function to only receive specific kwargs
, but I need to perform an identical operation with all of them, which I can put into a for
loop.
def my_func(kwarg1=None, kwarg2=None, kwarg3=None):
kwargs = {} # After somehow getting all my kwargs into a dictionary
for k in kwargs:
# Do my operation
I do not want my function to receive an arbitrary number of kwargs
, but I do want to access my kwargs
in a dictionary.
Assuming you have no positional arguments, you could get access to your kwargs via locals
if you put it at the top of your function:
def my_func(kwarg1=None, kwarg2=None, kwarg3=None):
# Don't add any more variables before the next line!
kwargs = dict(locals())
for k in kwargs:
# Do my operation
This is hacky (at best) and it's probably better to just spell it out:
kwargs = {'kwarg1': kwarg1, ...}
This is Python3.3+ code that creates the list of keyword argument names automatically. Just for completness. I would prefer any of the simpler solutions.
import inspect
def my_func(*, kwarg1=None, kwarg2=None, kwarg3=None):
local_vars = locals()
kwargs = {k: local_vars[k] for k in KWARGS_my_func}
print(kwargs)
KWARGS_my_func = [p.name for p in inspect.signature(my_func).parameters.values()
if p.kind == inspect.Parameter.KEYWORD_ONLY]
my_func(kwarg2=2)
Simply create a dictionary as normal, retrieving the values of each argument.
def my_func(kwarg1=None, kwarg2=None, kwarg3=None):
kwargs = {'kwarg1':kwarg1, 'kwarg2':kwarg2, 'kwarg3':kwarg3}
for k in kwargs:
# Do my operation
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.