[英]Explicitly declaring variable as unused in Python/PyCharm
Is there a way to declare a variable as unused in PyCharm, or in Python in general, so you can explicitly tell the compiler not to give a warning about it? 有没有办法在PyCharm或Python中将变量声明为未使用,因此您可以明确告诉编译器不要发出警告?
I am not talking about the convention of naming unused variables for the programmer (often named "_" or "__"), but an option to explicitly mark a variable as unused for the compiler, for example in a loop. 我不是在讨论为程序员命名未使用的变量的惯例(通常命名为“_”或“__”),而是一个显式地将变量标记为编译器未使用的选项,例如在循环中。 I also don't just want to disable inspections in general.
我也不仅仅想要禁用检查。
I've heard that you can do this in PyDev by beginning the variable name with "unused", and I thought this might exist in PyCharm as well, but couldn't find it yet. 我听说你可以在PyDev中通过使用“unused”开始变量名来做到这一点,我认为这也可能存在于PyCharm中,但还是找不到它。
You can disable this inspection either for a single statement like: 您可以对以下单个语句禁用此检查:
# noinspection PyUnusedLocal
unused_thing = something()
or for a whole function (or class) by placing the comment above the function (or class): 或者通过将注释放在函数(或类)上面来完成整个函数(或类):
# noinspection PyUnusedLocal
def foo():
unused_thing = something()
For some reason this particular inspection cannot be switched off via the inspections context menu... maybe worth a pycharm ticket. 由于某种原因,无法通过检查上下文菜单关闭此特定检查......可能值得一张pycharm票。
You can easily and least intrusively ignore pycharm unused local
warnings (only) for unused function parameters by prefixing them with underscores. 您可以通过在前缀下加下划线来轻松且最不干扰地忽略
unused local
使用的函数参数的pycharm unused local
警告(仅) 。
Eg 例如
In the following code, pycharm will not warn about the unused parameter _bar
在以下代码中,pycharm不会警告未使用的参数
_bar
def foo(_bar):
print("nothing here")
I've noticed that using a single underscore for the throwaway variable name seems to bypass this check. 我注意到,对于一次性变量名使用单个下划线似乎绕过了这个检查。 I'm using PyCharm 2016.1.3.
我正在使用PyCharm 2016.1.3。
for _ in range(3):
pass
Another way, similar to UNUSED
in C++ ( here ), which works if you want to hide the warning on a specific function parameter but keeps the warning enabled for the rest of the function: 另一种方式,类似于C ++中的
UNUSED
( 此处 ),如果您想隐藏特定函数参数的警告但仍保持为该函数的其余部分启用警告,则该方法有效:
# noinspection PyUnusedLocal
def UNUSED(*args, **kwargs):
pass
def my_function(alpha, beta, gamma):
UNUSED(gamma)
return alpha + beta
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.