Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicitly declaring variable as unused in Python/PyCharm

Tags:

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?

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.

like image 386
Raimund Krämer Avatar asked Sep 16 '15 08:09

Raimund Krämer


People also ask

How do you handle unused variables in Python?

To suppress the warning, one can simply name the variable with an underscore ('_') alone. Python treats it as an unused variable and ignores it without giving the warning message.

How do I find unused variables in Pycharm?

In the Settings open Editor -> Inspections. In the list in the middle open the python category and look for "Unused local" (it is sorted alphabetically). That should be checked. Also check your color settings in case the variable simply doesn't get highlighted the way you want it.


1 Answers

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.

like image 157
sebastian Avatar answered Sep 19 '22 07:09

sebastian