Skip to main content
 首页 » 编程设计

python之如何在 python 中检测不正确的 kwarg 名称

2024年11月24日12pengyingh

我刚刚发现函数 pandas.read_excel() 的 kwarg skip_footer 在版本 0.23.0 中被弃用,现在称为 skipfooter。 skip_footer 似乎被默默地忽略了,这使得弄清楚为什么我的代码停止正常工作变得更加困难。

编辑:

Ok, I lied: I was actually using pandas.ExcelFile.parse(). The documentation suggests they take the same arguments, but in the source code there appear to be some small differences--including with this parameter. I am not suppressing or ignoring warnings (to the best of my knowledge)

当我使用不正确的 kwarg 时,有没有办法获得警告或异常来提醒我?

请您参考如下方法:

查看 pandas.ExcelFile.parse() 源代码,它不检查 **kwds 中的 skip_footer ,它使用的底层方法和函数也没有。

所以它确实会默默地忽略大多数未知的关键字。

虽然 Python 提示缺少位置参数,但它无法检查关键字参数。 AFAIK,语言中没有内置机制来实现这一点。

可以编写个别函数来拒绝无效关键字:

def kwtest(**kwds): 
     allowed = {'spam', 'eggs', 'cheese'} 
     invalid = set(kwds.keys()) - allowed 
     if invalid: 
         raise ValueError(f'invalid keyword arguments {invalid}') 

(旧答案)

根据documentation和 code对于 Pandas,skip_footer 关键字参数仍然存在。

但是,read_excel 函数标有 @deprecate_kwarg 装饰器用于 skip_footer。据我所知,使用 skip_footer 关键字参数应该引发FutureWarning 异常。

您是否可能抑制或忽略警告?