28

I'm updating some code to PEP 8 standard using pylint. Part of the code is throwing the W0612 unused variable error but it's because it's using a module that returns (x,y) for example when only x is needed in this particular case, this is what's done.

(var_1, var_2) = func()

def func():
    a="a"
    b="b"
    return (a,b)

var_1 is then returned but var_2 is never used and therefore throws the error. How should I handle this? I'm thinking this

var = func()[0]

What is the best way to handle it?

Chris Martin
  • 30,334
  • 10
  • 78
  • 137
Jacxel
  • 1,634
  • 8
  • 22
  • 33

1 Answers1

41

I believe that a, dummy = func() does the trick. Pylint allows (if I recall correctly) unused variables names that start with _ or dummy, e.g. dummy_index.

You can configure this by passing --dummy-variables-rgx option to Pylint. This specifies the regex that catches dummy variable names.

From Pylint 1.6.0 documentation:

dummy-variables-rgx:

    A regular expression matching the name of dummy variables (i.e. expectedly not used).     Default: (_+[a-zA-Z0-9]*?$)|dummy

Note: Using _ can indeed cause confusion (props: Sven Marnach). There's a convention to use single underscore as prefix for semi-private identifiers, the double underscore is of course the prefix for special Python methods and on top of that there's a convention to aliasgettext() function as _() in programs that need localization as in _("text to translate").

Bartleby
  • 1,144
  • 1
  • 13
  • 14
Rafał Dowgird
  • 43,216
  • 11
  • 77
  • 90
  • 2
    Yes that's perfect `unused_index` didn't work, `_unused_index` and `_index` did though. thanks for your help. – Jacxel Apr 11 '12 at 14:02
  • 4
    I recommend to use `dummy` over a mere `_` as a variable name. The latter usually causes unnecessary confusion. – Sven Marnach Apr 11 '12 at 14:02
  • @Jacxel I was wrong about the `unused` prefix. This is what we used in a codebase I used to work on. The Pylint default is `dummy` or `_`. – Rafał Dowgird Apr 11 '12 at 14:03
  • 4
    If you don't like these conventions, I think you can add other alternatives by using a pylintrc file. You can also disable pylint warnings on individual lines by adding a comment like `#pylint: disable=X0123` (see the [official documentation](http://www.logilab.org/card/pylint_manual)). – James Apr 11 '12 at 14:03
  • @SvenMarnach agreed. Edited to include this. – Rafał Dowgird Apr 11 '12 at 14:10
  • Alternatively, to make it so that `unused` and `dummy` are both acceptable prefixes for unused variables (but `_` isn't), modify the dummy variables line in `~/.pylintrc` to be: `dummy-variables-rgx=unused|dummy`. Do this if it is more convenient for you than using the corresponding command line option. – John1024 Dec 19 '18 at 06:30