2

I saw functions returning tuples and at receiving end, sometimes I see syntax something like this.

def foo():
    return (True, False)

foo, __ = foo()

The thing I investigated is that, __ (double underscore) don't give pep8 error as if its not being used anywhere.

Seeking:

  1. the practice situation where we should use this
  2. Situations we should avoid
  3. Any alternatives.
rmunn
  • 29,094
  • 9
  • 62
  • 91
A.J.
  • 6,664
  • 10
  • 55
  • 74

1 Answers1

4

As Andrés Pérez-Albela H. has mentioned, double underscores are usually used for "magic methods" like __init__(). In that usage, they lead and trail the method name. A single underscore in front of a method (or variable) name, like _index, usually means "this is a private member variable or a private method, and should not be used by other code". This is simply convention and does not have any special meaning to the Python interpreter, whereas some double-underscore methods do have special meaning.

Now, as for the question you asked: __ (a double underscore) as a variable name is not a normal thing in Python coding. The more usual convention is to use _ (a single underscore) for any variable whose contents you don't need. See What is the purpose of the single underscore "_" variable in Python? for more details.

However, there are sometimes reasons why a programmer might want to avoid using _ as a variable name. Specifically, if he's running code in an interactive Python interpreter session. In an interactive session, the value returned from the previous expression is stored in a variable named _. So if you're used to using _ as "a variable whose contents I don't care about" but you're in an interactive Python interpreter session, you might switch to using __ for that purpose instead.

So my best guess is that the sample code you've seen was intended to be run in an interactive Python session, where _ already has a special meaning. And so the person writing the code used __ for his throwaway variables, instead of _ which would be more commonly used.

Community
  • 1
  • 1
rmunn
  • 29,094
  • 9
  • 62
  • 91
  • 2
    When you say "the Python interpreter", I think you should instead be specifying an *interactive* interpreter session. Even when you run a script, the "interpreter" is still being used, you just don't interact with it directly as a user. – Blckknght Dec 03 '15 at 06:50
  • 1
    @Blckknght - Good point. I've updated my answer to be clearer. Thanks! – rmunn Dec 03 '15 at 06:52
  • Well explained, Thanks. I got what you mean. +1 – A.J. Dec 03 '15 at 07:52