我想知道只有在调用关键字参数时才对关键字参数执行操作的最佳(最pythonic和/或优雅)方法是什么。类似的东西:
import keyword
def (*arg, **kwargs):
if keyword.iskeyword(parameter):
# Do stuff involving parameter
# Do other stuff
return 0
答案 0 :(得分:3)
检查预期的密钥是否在kwargs
参数中:
def foo(*arg, **kwargs):
if 'bar' in kwargs:
print('You called foo with bar={}'.format(kwargs['bar']))
else:
print('You didn't use the "bar" keyword argument')