Python kwargs 过滤器附加功能

问题描述

我有一本字典,我想将它传递给 matplotlib 以绘制条形图,这很简单,但有点像这样:

import matplotlib.pyplot as plt

#This works fine:
plt.bar(x=range(3),height=[300,128,581],width=0.8,align='edge')

#This also works fine:
mydict = {'x':range(3),'height':[300,'width':0.8,'align':'edge'}
plt.bar(**mydict)

#But adding in something extra to my dictionary which might be there for other reasons screws it up:
mydict = {'x':range(3),'align':'edge','fruit':'bananas'}
plt.bar(**mydict)

#/usr/local/python3/lib/python3.6/site-packages/matplotlib/pyplot.py in bar(x,height,width,bottom,#align,data,**kwargs)
#   2432     return gca().bar(
#   2433         x,width=width,bottom=bottom,align=align,#-> 2434         **({"data": data} if data is not None else {}),**kwargs)
#   2435 
#   2436 

我查看了并且可以看到我可以使用 inspect获取函数和参数的详细信息。 inspect.signature(plt.bar) 给出:

这对于从我的字典中删除不在此列表中的内容很有用,但后来我从 the documentation 知道还有其他可选的 kwarg,例如 linewidth登录

如果它们存在,我不想过滤掉它们,但我无法找到一种列出可能的 kwargs 和 args 的方法

解决方法

可能是这样的

import matplotlib.pyplot as plt

# #But adding in something extra to my dictionary which might be there for other reasons screws it up:
required = {'x':range(3),'height':[300,128,581]}
optional = {'width':0.8,'align':'edge','fruit':'bananas'}
mybar = plt.bar(**required)
for key,value in optional.items():
    try:
        setattr(mybar,key,value)
    except AttributeError:
        pass
plt.show()