Reputation: 9025
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.
Upvotes: 3
Views: 123
Reputation: 36708
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.
Upvotes: 4