Python kwargs过滤器附加
我有一个字典,我想传递给matplotlib以绘制条形图,这是简化它,但有点像这样:Python kwargs过滤器附加,python,keyword-argument,Python,Keyword Argument,我有一个字典,我想传递给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,128,581],'width':0.8,'align':'e
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,128,581],'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),'height':[300,128,581],'width':0.8,'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, height, width=width, bottom=bottom, align=align,
#-> 2434 **({"data": data} if data is not None else {}), **kwargs)
# 2435
# 2436
我已经看过了,我可以使用inspect
来获取函数和参数的详细信息<代码>检查签名(打印条)给出:
这对于从我的字典中删除不在此列表中的内容非常有用,但是我知道还有其他可选的Kwarg,例如线宽和日志
如果它们存在,我不想过滤掉它们,但我无法找到一种方法来列出可能的Kwarg和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()
**kwargs将接受您在dict中抛出的所有内容,无需删除不受支持的kwargs-它们将在代码中被忽略。否则-文档是检查可用可选参数的地方。@buran这是我的想法,但我在代码中进一步得到的AttributeError是
“矩形”对象没有属性“水果”
谢谢,我没有使用setattr()以前,但这似乎是一个很好的解决方法,这是一种解决方法。我不知道它应该由matplotlib
处理,所以可能有一些选项我不知道。如果有人提出不同的解决方案,那会很有趣。