用于将函数作为属性进行比较的 Python 代码检查器
我偶尔会花费大量时间来追踪代码中的脑残……虽然我通常会针对它运行 pylint,但有些东西会忽略 pylint。对我来说最容易忽视的问题是……
# normally, variable is populated from parsed text, so it's not predictable
variable = 'fOoBaR'
if variable.lower == 'foobar':
# ^^^^^<------------------ should be .lower()
do_something()
pylint 和 Python 都没有对此提出异议……是否有一个 python 代码检查工具可以标记这个特定问题?
I occasionally spend a considerable amount of time tracking down brainfarts in my code... while I normally run pylint against it, there are some things that slip past pylint. The easiest problem for me to overlook is this...
# normally, variable is populated from parsed text, so it's not predictable
variable = 'fOoBaR'
if variable.lower == 'foobar':
# ^^^^^<------------------ should be .lower()
do_something()
Neither pylint nor Python bark about this... is there a python code-checking tool that can flag this particular issue?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您建议如何使用代码检查器来验证这一点?这是完全合法的语法。与其检查此类错误,不如养成使用更好模式的习惯。
而不是:这样
做:
这样,您总是显式地对要比较的值调用
.lower()
,而不是依赖就地方法调用和比较,这会导致到你正在经历的陷阱。How do you propose a code-checker validate this? It's perfectly legitimate syntax. Rather than checking for this kind of mistake, it would be better to get into the habit of using better patterns.
Instead of:
Do this:
This way you're always explicitly calling
.lower()
on the value you're comparing against, instead of relying on an in-place method-call and comparison, which leads to the very pitfall you're experiencing.@Mike Pennington 我只想首先说我也经常遇到这种情况 -.-
@eyquem 'lower()' 是一个函数。 “lower”是一个函数指针(如果我没记错的话)。 Python 将允许您尝试运行此代码,但不会调用该函数。
我认为这很难捕捉的原因是你并不总是知道你调用方法的变量的类型。例如,假设我有 2 节课。
如果您的代码中有一个函数接受参数“baz”,如下所示:
根据 baz 的类型,其中任何一个都可能有效。
但实际上无法知道 baz 的类型是“Foo”还是“Bar”。
编辑:我的意思是静态分析......
@Mike Pennington I just want to first say that I also run into this a lot -.-
@eyquem 'lower()' is a function. 'lower' is a function pointer (if I'm not mistaken). Python will let you attempt to run this code, but it will not invoke the function.
I think the reason this is hard to catch is that you don't always know the type of the variable which you're calling methods on. For example, say I have 2 classes.
If your code has a function in it that takes an argument 'baz' like so:
Either one of these could be valid depending on baz's type.
There is literally no way of knowing if baz is of type 'Foo' or 'Bar', though.
EDIT: I meant with static analysis...
这是 pylint 票证#65910
This is pylint ticket #65910