1

I recently discovered that I could use _ as a variable.

Is there a particular protocol of when to use this as a variable name? Should __ ever be used?

Example from deeplearning.net with the Theano library, there is a trend to use _ when defining theano.scan() operations...

values, _ = theano.scan(power_of_2,
                        outputs_info = T.constant(1.),
                        non_sequences = max_value,
                        n_steps = 1024)
Alexander McFarlane
  • 10,643
  • 9
  • 59
  • 100
  • Could you untag `theano`? It seems an inappropriate tag because this question is extremely general and it is a duplicate of a [duplicate](http://stackoverflow.com/questions/1739514/underscore-as-variable-name-in-python) – eickenberg May 24 '15 at 09:34

4 Answers4

5

_ are usually used when you are going to discard its value (i.e not use its value), or in local variables. But that's a convention, of course.

For example, you have a function that returns a tuple but you are only interested in the first element of the tuple, so

var, _ = func(args)

Would be how you conventionally use it.
Another example consists in, for instance, repeating something x times but not really using the value in the range, so you could do:

for _ in range(10):
    #blablabla

But bear in mind that these are only conventions made up by programmers, and do not follow any kind of rule, although it is considered good programming practise not to use _ as variable names which you are going to use.

rafaelc
  • 57,686
  • 15
  • 58
  • 82
1

_ is conventionally used as a variable name in unpacking expressions for unpacked components which aren't needed and will be ignored.

Benjamin Peterson
  • 19,297
  • 6
  • 32
  • 39
1

_ and dummy are treated specially by pylint - they are variables you can assign things to without getting a "variable set but not used" warning.

dstromberg
  • 6,954
  • 1
  • 26
  • 27
1

Although it was used to represent an unused variable, nowadays it is recommended against using _, because it usually has it's own special purposes depending on the library used, such as in Django it is usually associated with translation.

You should come up with another meaningful variable name when you unpack tuples.

Community
  • 1
  • 1
jamylak
  • 128,818
  • 30
  • 231
  • 230