python _ underscore variable
来源:互联网 发布:杭州真趣网络 编辑:程序博客网 时间:2024/05/18 00:14
What is the purpose of the single underscore “_” variable in Python?
What is the meaning of _
after for
in this code?
if tbh.bag: n = 0 for _ in tbh.bag.atom_set(): n += 1
2 Answers
_
has 3 main conventional uses in Python:
- To hold the result of the last executed statement in an interactive interpreter session. This precedent was set by the standard CPython interpreter, and other interpreters have followed suit
- For translation lookup in i18n (imported from the corresponding C conventions, I believe), as in code like:
raiseforms.ValidationError(_("Please enter a correct username"))
- As a general purpose "throwaway" variable name to indicate that part of a function result is being deliberately ignored, as in code like:
label, has_label, _ = text.partition(':')
The latter two purposes can conflict, so it is necessary to avoid using _
as a throwaway variable in any code block that also uses it for i18n translation (many folks prefer a double-underscore, __
, as their throwaway variable for exactly this reason).
_
is the name used for the function that does internationalisation and localisation string translation lookups. I'm pretty sure it is the C gettext
library that established that convention. – ncoghlan May 19 '11 at 16:47 __
(a double underscore) as my general purpose throwaway variable to avoid conflicting with either of the first two use cases. – ncoghlan Mar 20 '12 at 6:35_
as a variable name for a throwaway variable isn't mentioned in PEP 8. Do you know of an authoritative source that suggests using it for that purpose? – martineau Jun 23 '15 at 19:30_
used as a variable name since I started using Python professionally in 2002. – ncoghlan Jun 28 '15 at 3:54a, __, c = iterable
tells the reader immediately that we're unpacking a 3-tuple, but only using the first and last values. If we instead write a, b, c = iterable
, the reader (or an automated code linter) can reasonably expect all of a
, b
, and c
to be used later (and if they're not, it may be a sign of a bug somewhere). – ncoghlan Feb 29 at 7:42It's just a variable name, and it's conventional in python to use _
for throwaway variables. It just indicates that the loop variable isn't actually used.
This question already has an answer here:
- What is the purpose of the single underscore “_” variable in Python? 2 answers
Peter Norvig has an essay describing a program to solve sudoku puzzles, even the hardest ones, by combining deterministic logical operations and smart traversal of the possible solutions. The latter is done recursively; here's that function (source):
def search(values): "Using depth-first search and propagation, try all possible values." if values is False: return False ## Failed earlier if all( len( values[s]) == 1 for s in squares): return values ## Solved! ## Chose the unfilled square s with the fewest possibilities _,s = min( (len( values[s]), s) for s in squares if len(values[s]) > 1 ) return some( search( assign( values.copy(), s, d)) for d in values[s] )
(I've added some spaces, CRs, and tabs for the sake of my eyes; apologies to Dr. Norvig.)
Right below the comment there's a line starting with "_,s
". That seems to be the unpacked tuple (len(values[s]),s
) with the minimal value of s
. Is Dr. Norvig using "_
" as a variable name just to indicate it's a "don't care" result, or is something else going on? Are there times when "_
" is recommended as a variable name? In interactive mode, "_
" holds the answer of the previous operation; is there a similar function in non-interactive code?
Update
Thanks for the good answers. I guess The Answer goes to Alex Martelli for "value added"; he points out that the "_, vbl_of_interest" idiom is often a side effect of the DSU idiom, which itself has been made largely unnecessary.
marked as duplicate by poke Nov 12 '14 at 20:48
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
_
and just put [1]
after the method call to project out the wished results. – Trilarion May 20 '14 at 8:253 Answers
Yep, _
is a traditional name for "don't care" (which unfortunately clashes with its use in I18N, but that's a separate issue;-). BTW, in today's Python, instead of:
_,s = min( (len( values[s]), s) for s in squares if len(values[s]) > 1 )
you might code
s = min((s for s in squares if len(values[s])>1), key=lambda s: len(values[s]))
(not sure what release of Python Peter was writing for, but the idiom he's using is an example of "decorate-sort-undecorate" [[DSU]] except with min instead of sort, and in today's Python the key=
optional parameter is generally the best way to do DSU;-).
heapq
's function don't accept key=
-- neither do bisect
's, but that's not quite as common a use case for me as priority queues;-). – Alex Martelli Nov 16 '09 at 1:33You are correct. In non-interactive mode _
has no special meaning. Indeed, Norvig just wants to convey that he doesn't care about the value of that variable.
Offtopic: That article by Norvig is very nice. A recommended read.
Your interpretation is correct. Outside of the special meaning in interactive mode _
is just used as a "don't care" variable name, especially in unpacking.
len(tbh.bag.atom_set())
(if the returned value has a__len__
method) orsum(1 for _ in tbh.bag.atom_set())
– Nick T Apr 5 at 20:08