I saw this code snippet:
sock.listen(20)
for _ in range(20):
newsock, client_addr = sock.accept()
print "Client connected:", client_addr
data[newsock] = ""
why use _ for this example? Is there any
optimization to be had using it?
I know that in the interpreter _ means the
last value calculated, but what does _ mean
inside source code? 37 40375
In article <2m************@uni-berlin.de>,
Jon Perez <jb********@wahoo.com> wrote: I saw this code snippet:
sock.listen(20) for _ in range(20): newsock, client_addr = sock.accept() print "Client connected:", client_addr data[newsock] = ""
why use _ for this example? Is there any optimization to be had using it?
I know that in the interpreter _ means the last value calculated, but what does _ mean inside source code?
AFAIK it's just a variable like any other, but by convention it means
that you don't intend to use that value, just read it and ignore it.
--
David Eppstein
Computer Science Dept., Univ. of California, Irvine http://www.ics.uci.edu/~eppstein/
In article <ep****************************@news.service.uci.e du>,
David Eppstein <ep******@ics.uci.edu> wrote: In article <2m************@uni-berlin.de>, Jon Perez <jb********@wahoo.com> wrote:
I saw this code snippet:
sock.listen(20) for _ in range(20): newsock, client_addr = sock.accept() print "Client connected:", client_addr data[newsock] = ""
why use _ for this example? Is there any optimization to be had using it?
I know that in the interpreter _ means the last value calculated, but what does _ mean inside source code?
AFAIK it's just a variable like any other, but by convention it means that you don't intend to use that value, just read it and ignore it.
I've never heard of that convention before. Is it some python-specific
thing, or is my ignorance more global in scope?
In any case, I'd vote for some more useful variable name. In the above
case, something like connectionNumber or whatever would be more
self-explanitory.
Roy Smith <ro*@panix.com> writes: I've never heard of that convention before. Is it some python-specific thing, or is my ignorance more global in scope?
It may derive from Prolog, where you use _ as an unbound "wildcard".
E.g. to declare that X is a parent if X is a father or mother:
parent(X) :- fatherOf(X, _), !.
parent(X) :- motherOf(X, _), !.
because you don't need to know anything about the child, just that it
exists. If you used a variable like Y, you would either also need to
say something about Y, or Y would end up in the resolved answer.
(The ! is a "cut", and means we're not interested in more than one
answer.)
Tor Iver Wilhelmsen wrote: Roy Smith <ro*@panix.com> writes:
I've never heard of that convention before. Is it some python-specific thing, or is my ignorance more global in scope?
It may derive from Prolog, where you use _ as an unbound "wildcard". E.g. to declare that X is a parent if X is a father or mother:
It may, but to answer the original poster's question, it's not uncommon
to see this in other languages (where _ is a valid identifier). _ often
means a variable one's not interested in the value of, but which is
needed for syntactic reasons.
Note that _(...) as a macro call has another conventional meaning, which
comes from gettext, where one uses _("string literal") to indicate a
string that needs localization.
Note also there's a noticeable difference between the anonymous variable
in Prolog and the use of _ in Python; in Prolog, the anonymous variable
can be used multiple times in the same expression and there is no need
for the variable to represent the same thing. In
middle(X) :- inOrder(_, X, _).
there's no need for _ to map to the same object -- middle(c) would be
true even if inOrder(b, c, d) were the only known relevant fact, and b
and d are certainly not equal. That's not true in Python, where _ is
just another name with no special semantics.
--
__ Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
/ \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
\__/ Never be the first to believe / Never be the last to deceive
-- Florence, _Chess_
Roy Smith wrote: I've never heard of that convention before. Is it some python-specific thing, or is my ignorance more global in scope?
I have seen it in logic and functional programming, where '_' -
differently from python - has a special meaning: assignments to '_' are
discarded in functional programming and
I guess that it's value in the interpreter, instead, comes from perl's $_.
In any case, I'd vote for some more useful variable name. In the above case, something like connectionNumber or whatever would be more self-explanitory.
In that case, I interpret is as this: that loop has to be iterated 20
times, and the looping variable is uninfluent. In this cases, again by
convention, in C programs the variable is often called "i".
--
Ciao,
Matteo
Whoops, part missing :-)
Matteo Dell'Amico wrote: I have seen it in logic and functional programming, where '_' - differently from python - has a special meaning: assignments to '_' are discarded in functional programming and
in logic programming it is seen as a jolly "match-all" value.
--
Ciao,
Matteo
"David Eppstein" <ep******@ics.uci.edu> wrote in message
news:ep****************************@news.service.u ci.edu... In article <2m************@uni-berlin.de>, Jon Perez <jb********@wahoo.com> wrote:
I saw this code snippet:
sock.listen(20) for _ in range(20): newsock, client_addr = sock.accept() print "Client connected:", client_addr data[newsock] = ""
why use _ for this example? Is there any optimization to be had using it?
I know that in the interpreter _ means the last value calculated, but what does _ mean inside source code? AFAIK it's just a variable like any other, but by convention it means that you don't intend to use that value, just read it and ignore it.
What convention? I have to agree with a couple
of other posters; I've never heard of it before.
If it really is a convention, it would be nice to have it
documented somewhere (like the single underscore
in front of a variable means "weak internal use").
Somewhere is most likely PEP 8 - the Python
Style Guide.
John Roth -- David Eppstein Computer Science Dept., Univ. of California, Irvine http://www.ics.uci.edu/~eppstein/
John Roth wrote: What convention? I have to agree with a couple of other posters; I've never heard of it before.
If it really is a convention, it would be nice to have it documented somewhere (like the single underscore in front of a variable means "weak internal use"). Somewhere is most likely PEP 8 - the Python Style Guide.
A convention doesn't need to have official sanction to be a convention.
--
__ Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
/ \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
\__/ But you're not going to be there tomorrow. And it's all about
tomorrow. -- Montgomery Brogan
John Roth wrote: "David Eppstein" <ep******@ics.uci.edu> wrote: Jon Perez <jb********@wahoo.com> wrote:I know that in the interpreter _ means the last value calculated, but what does _ mean inside source code?
AFAIK it's just a variable like any other, but by convention it means that you don't intend to use that value, just read it and ignore it.
What convention? I have to agree with a couple of other posters; I've never heard of it before.
I would imagine it's the same convention that suggests that
the value assigned to _ is ignored in the following type
of code, which surely most of us have seen around here a
few times:
a, b, _ = tupleWithThreeItems
-Peter
I must admit I've never heard of this before either but, I'm no world
authority on Python.
I've just tried it on some toy code and as always I run pychecker on it. So
with
def spam():
for i in range(10):
print 'a'
I get "Local variable (i) not used". But with the following:
def spam():
for _ in range(10):
print 'a'
I get no such warning. Is pychecker aware of this convention or is it
coincidental? I don't
know.
Michael Charlton
"David Eppstein" <ep******@ics.uci.edu> wrote in message
news:ep****************************@news.service.u ci.edu... In article <2m************@uni-berlin.de>, Jon Perez <jb********@wahoo.com> wrote:
I saw this code snippet:
sock.listen(20) for _ in range(20): newsock, client_addr = sock.accept() print "Client connected:", client_addr data[newsock] = ""
why use _ for this example? Is there any optimization to be had using it?
I know that in the interpreter _ means the last value calculated, but what does _ mean inside source code?
AFAIK it's just a variable like any other, but by convention it means that you don't intend to use that value, just read it and ignore it.
-- David Eppstein Computer Science Dept., Univ. of California, Irvine http://www.ics.uci.edu/~eppstein/
Michael Charlton wrote: I've just tried it on some toy code and as always I run pychecker on it. So with
def spam(): for i in range(10): print 'a'
I get "Local variable (i) not used". But with the following:
def spam(): for _ in range(10): print 'a'
I get no such warning. Is pychecker aware of this convention or is it coincidental? I don't
Found in Config.py:
_DEFAULT_UNUSED_LIST = [ '_', 'empty', 'unused', 'dummy', ]
Peter Is pychecker aware of this convention ...
Peter> Found in Config.py:
Peter> _DEFAULT_UNUSED_LIST = [ '_', 'empty', 'unused', 'dummy', ]
One might consider adding 'i' to that list. If nothing else, it would avoid
a bunch of warnings... ;-)
Skip
On Wed, 28 Jul 2004, Skip Montanaro wrote: Peter> _DEFAULT_UNUSED_LIST = [ '_', 'empty', 'unused', 'dummy', ]
One might consider adding 'i' to that list. If nothing else, it would avoid a bunch of warnings... ;-)
But then we'd have to add a, t, n, and x, too ;)
Skip Montanaro wrote: >> Is pychecker aware of this convention ...
Peter> Found in Config.py:
Peter> _DEFAULT_UNUSED_LIST = [ '_', 'empty', 'unused', 'dummy', ]
One might consider adding 'i' to that list. If nothing else, it would avoid a bunch of warnings... ;-)
All but "_" work as prefix, too, so that could avoid a bit too much...
Peter
> What convention? I have to agree with a couple of other posters; I've never heard of it before.
Coming from Fortran and C, I myself use i for 'don't care' looping vars.
If it really is a convention,
It is obviously not a universal convention. What does library code use?
it would be nice to have it documented somewhere (like the single underscore in front of a variable means "weak internal use"). Somewhere is most likely PEP 8 - the Python Style Guide.
In the interactive interpreter, _ is bound to the last expression evaluated
that is otherwise unassigned. a=3 _
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name '_' is not defined 3
3 _
3
This is the only official use of _ that I know of and it is documented
somewhere.
Terry J. Reedy
At Some Point, Someone Asked Something to The Effect of: where does this _ thing come from?
In ML, _ is used as magic "don't care" variable. It's often used when
unpacking tuples and some elements are irrelevant. Example:
Ocaml:
let (fu, bar, _, _) = returns_a_4_tuple ()
Python:
(fu, bar, _, __) = returns_a_4_tuple()
One difference is that _ is allowed multiple times in Ocaml, while in
Python it is not. Also to Python, it's a variable like any other, while
in Ocaml it's magic.
Phil Frost wrote: Python: (fu, bar, _, __) = returns_a_4_tuple()
One difference is that _ is allowed multiple times in Ocaml, while in Python it is not.
Why do you say that?
c:\>python
Python 2.3.4 (#53, May 25 2004, 21:17:02) .... a = 1, 2, 3, 4 b, c, d, e = a b, c, d, d = a b, c, _, _ = a _, _, _, _ = a _
4
Looks to me like Python doesn't care how many times it rebinds
a name while unpacking a tuple.
-Peter
Christopher T King wrote: On Wed, 28 Jul 2004, Skip Montanaro wrote:
One might consider adding 'i' to that list. If nothing else, it would avoid a bunch of warnings... ;-)
But then we'd have to add a, t, n, and x, too ;)
Don't forget j.
In article <Fa********************@powergate.ca>,
Peter Hansen <pe***@engcorp.com> wrote: Phil Frost wrote: One difference is that _ is allowed multiple times in Ocaml, while in Python it is not. Why do you say that?
c:\>python Python 2.3.4 (#53, May 25 2004, 21:17:02) .... >>> a = 1, 2, 3, 4 >>> b, c, d, e = a >>> b, c, d, d = a >>> b, c, _, _ = a >>> _, _, _, _ = a >>> _ 4
In that context, it's allowed multiple times, but in some other contexts
it's not: def foo(_,_): pass
....
File "<stdin>", line 1
SyntaxError: duplicate argument '_' in function definition
--
David Eppstein
Computer Science Dept., Univ. of California, Irvine http://www.ics.uci.edu/~eppstein/
David Eppstein wrote: In that context, it's allowed multiple times, but in some other contexts it's not:
def foo(_,_): pass
... File "<stdin>", line 1 SyntaxError: duplicate argument '_' in function definition
Uh, okay... and does Ocaml allow duplicating argument
names in whatever it has that passes for a function
definition? This is all a reach from the original
point of the thread, which was to use it as a throw-away
control variable in a for loop...
-Peter
David Eppstein wrote: def foo(_,_): pass
The best solution then would probably be:
def foo(*_):
pass
Peter Hansen wrote: Uh, okay... and does Ocaml allow duplicating argument names in whatever it has that passes for a function definition? This is all a reach from the original point of the thread, which was to use it as a throw-away control variable in a for loop...
It allows pattern-matching. You can say, for instance, something as:
foo(a, a) = True
foo(_, _) = False
This means that foo is true when its arguments are equal. Note, too,
that 'a' has a different value from '_'.
--
Ciao,
Matteo
Christopher T King <sq******@WPI.EDU> wrote in message news:<Pi**************************************@ccc 3.wpi.edu>... On Wed, 28 Jul 2004, Skip Montanaro wrote:
Peter> _DEFAULT_UNUSED_LIST = [ '_', 'empty', 'unused', 'dummy', ]
One might consider adding 'i' to that list. If nothing else, it would avoid a bunch of warnings... ;-)
But then we'd have to add a, t, n, and x, too ;)
In other languages, I've used "fcrt" as a dummy variable name, to
indicate that is only named because the Friendly Compiler Requires
This.
Matteo Dell'Amico wrote: Peter Hansen wrote:
Uh, okay... and does Ocaml allow duplicating argument names in whatever it has that passes for a function definition? This is all a reach from the original point of the thread, which was to use it as a throw-away control variable in a for loop...
It allows pattern-matching. You can say, for instance, something as:
foo(a, a) = True foo(_, _) = False
This means that foo is true when its arguments are equal. Note, too, that 'a' has a different value from '_'.
I have no idea what you are talking about; sorry. The "code"
you show is not valid, and since you aren't talking about a
function *definition* (where duplicate names are disallowed)
but apparently about calling a function, I can't see that this
has the slightest thing to do with the topic at hand.
Therefore I'm sure I misunderstood what you meant... please
explain.
-Peter
Peter Hansen wrote: I have no idea what you are talking about; sorry. The "code" you show is not valid, and since you aren't talking about a function *definition* (where duplicate names are disallowed) but apparently about calling a function, I can't see that this has the slightest thing to do with the topic at hand.
Of course this is not valid python code. :-)
This is a pseudo-functional language function definition. It is
specified by pattern matching:
foo(a, a) = True
means that calling foo with a tuple of two identical arguments returns
True, while
foo(_, _) = False
means that calling foo with a tuple of any two arguments returns False,
if the above condition isn't met.
The goal was to put into evidence the use of pattern-matching and '_'.
That's all. :-)
I hope this is clearer now...
--
Ciao,
Matteo
Matteo Dell'Amico wrote: Peter Hansen wrote: I have no idea what you are talking about; sorry.
[...snip attempted explanation...]
I hope this is clearer now...
Actually, not in the least, but I'm happy to go on faith that
you have a point and hope you have managed to communicate it
to others. :-|
-Peter
Peter Hansen wrote: Actually, not in the least, but I'm happy to go on faith that you have a point and hope you have managed to communicate it to others. :-|
Let's try it again: in functional programming languages, you can use
pattern-matching, so that you can define functions in a declarative
fashion this way:
f(1) = 2
f(2) = 3
f(3) = 4
f(_) = 42
In python, this could be written as:
def f(x):
if x == 1:
return 2
elif x == 2:
return 3
elif x == 3:
return 4
else:
return 42
'_' is the identifier that means "anything here".
--
Ciao,
Matteo
Matteo Dell'Amico wrote: Peter Hansen wrote:
Actually, not in the least, but I'm happy to go on faith that you have a point and hope you have managed to communicate it to others. :-|
Let's try it again: in functional programming languages, you can use pattern-matching, so that you can define functions in a declarative fashion this way:
Oh! Enlightment dawns.... we were still talking about Ocaml then.
I see.
So to get this back to the point that was being made:
Phil said Ocaml allowed multiple _ in tuple assignments but
that Python did not, while I attempted to correct that assertion by
showing that it in fact did.
David and you were discussing a case involving function languages,
which Python is not, where the use of multiple _ (which now has
syntactical meaning, as opposed to being just an "ignore this" by
convention) is allowed.
Sounds to me like the two discussions are unrelated.
-Peter
Peter Hansen wrote: Phil said Ocaml allowed multiple _ in tuple assignments but that Python did not, while I attempted to correct that assertion by showing that it in fact did.
David and you were discussing a case involving function languages, which Python is not, where the use of multiple _ (which now has syntactical meaning, as opposed to being just an "ignore this" by convention) is allowed.
Sounds to me like the two discussions are unrelated.
More or less so. It was only a discussion on the etimology of the
underscore convention. :-)
--
Ciao,
Matteo
Matteo Dell'Amico wrote: Peter Hansen wrote: Sounds to me like the two discussions are unrelated.
More or less so. It was only a discussion on the etimology of the underscore convention. :-)
In that case they would be related, but is this any more than
supposition on your part? Is the use of _ as a throw-away in
for loops, and perhaps even in the interpreter as "last result",
definitely descended from its wildcard usage in functional
languages (or, at least, Ocaml)?
-Peter
On Thu, 29 Jul 2004, Peter Hansen wrote: In that case they would be related, but is this any more than supposition on your part? Is the use of _ as a throw-away in for loops, and perhaps even in the interpreter as "last result", definitely descended from its wildcard usage in functional languages (or, at least, Ocaml)?
I'm pretty sure they're both descended from the use of _ as both a
throw-away and a wildcard in Prolog, as another poster pointed out.
For reference, Prolog was born in 1970, OCaml was born in 1996 (with roots
dating back to ML in 1983), and Python was born in 1991. (Data gleaned
from the Programming Language Genealogy Project at everything2.com.)
Christopher T King wrote: On Thu, 29 Jul 2004, Peter Hansen wrote:In that case they would be related, but is this any more than supposition on your part? Is the use of _ as a throw-away in for loops, and perhaps even in the interpreter as "last result", definitely descended from its wildcard usage in functional languages (or, at least, Ocaml)?
I'm pretty sure they're both descended from the use of _ as both a throw-away and a wildcard in Prolog, as another poster pointed out.
I'm just as unsure about any of that. It seems more likely to
me that a number of people have independently found _ to be a handy
"anonymous" variable in different situations, and that trying to find
links to analogous usage in other languages is largely speculative.
Of course, that said, we'll probably hear shortly from someone
channelling the person who added it to the interpreter as the
"last result" name, contra-dicting me. :-)
-Peter
Peter Hansen wrote: I'm just as unsure about any of that. It seems more likely to me that a number of people have independently found _ to be a handy "anonymous" variable in different situations, and that trying to find links to analogous usage in other languages is largely speculative.
It would surprise me if the three were unrelated... there are
similarities between prolog's unification, ML's pattern matching and
python's tuple unpacking (even if the latter is considerably simpler and
less powerful), and note that the specific meaning of _ - both in Prolog
and in ML-like languages - is "throw away": if I'm not mistaken, you can
always replace an underscore with a new unused variable.
Of course, that said, we'll probably hear shortly from someone channelling the person who added it to the interpreter as the "last result" name, contra-dicting me. :-)
I see this one as a totally unrelated meaning, similar to perl's $_. I'm
waiting to be contradicted, too. :-)
--
Ciao,
Matteo
In article <41***************@alcyone.com>, Erik Max Francis wrote: Note also there's a noticeable difference between the anonymous variable in Prolog and the use of _ in Python; in Prolog, the anonymous variable can be used multiple times in the same expression and there is no need for the variable to represent the same thing. In
middle(X) :- inOrder(_, X, _).
In Python, it's possible to use _ multiple times in the same expression,
too. I guess there's no obvious reason why this shouldn't work, but I
discovered the following tuple-unpacking idiom recently: for _, val, _ in ((1, 2, 3), (4, 5, 6), (7, 8, 9)):
.... print val
....
2
5
8
--
.:[ dave benjamin: ramen/[sp00] -:- spoomusic.com -:- ramenfest.com ]:.
"When the country is confused and in chaos, information scientists appear."
Librarian's Lao Tzu: http://www.geocities.com/onelibrarian.geo/lao_tzu.html
"Dave Benjamin" <ra***@lackingtalent.com> wrote in message
news:slrncgj6j3.vte.ra***@lackingtalent.com... In Python, it's possible to use _ multiple times in the same expression,
In Python, _ is a (non-keyword) name like any other. It can be used like
any other name. In interactive mode, it is the default name bound to bare
expressions, but it is still just a name.
too. I guess there's no obvious reason why this shouldn't work, but I discovered the following tuple-unpacking idiom recently:
for _, val, _ in ((1, 2, 3), (4, 5, 6), (7, 8, 9)): ... print val ... 2 5 8
So does for a,v,a in [[1,2,3], [4,5,6]]: print v
....
2
5
too much fuss over simplicity yours
Terry J. Reedy
Dave Benjamin <ra***@lackingtalent.com> writes: In Python, it's possible to use _ multiple times in the same expression,
There is, however, one objection to the use of _ as a placeholder for
a dummy variable: it is used by the gettext module. So if a program
may be subject to internationalization, it is advisable to keep this
name reserved, or you may run into problems.
Heike> Dave Benjamin <ra***@lackingtalent.com> writes: In Python, it's possible to use _ multiple times in the same expression,
Heike> There is, however, one objection to the use of _ as a placeholder
Heike> for a dummy variable: it is used by the gettext module. So if a
Heike> program may be subject to internationalization, it is advisable
Heike> to keep this name reserved, or you may run into problems.
Only if you use it as both a placeholder variable and call it as a function
within the same function, or have the misfortune to declare
global _
in some function where it's used as a placeholder in a module whose other
functions call _("some string").
Skip This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
by: Steve Richter |
last post by:
What does the "." mean in the following sql script stmts?
use
GO
if exists (select * from dbo.sysobjects where
id = object_id(N'.')
and OBJECTPROPERTY(id,N'IsUserTable') = 1)
drop table ....
|
by: RobertTG |
last post by:
Someone please translate the code below into English...
Particularly the indicated line
Thanks
function attachComment()
{
var aForms = document.getElementsByTagName("FORM");
for (var i = 0;...
|
by: allenj |
last post by:
DB21085I Instance "md" uses "32" bits and DB2 code release "SQL08012"
with level identifier "02030106".
Informational tokens are "DB2 v8.1.0.16", "s030508", "MI00048", and
FixPak "2". Product is...
|
by: Larry David |
last post by:
Ok, first of all, let's get the obvious stuff out of the way. I'm an idiot. So please indulge me for a moment. Consider it an act of "community service"....
What does "64bit" mean to your friendly...
|
by: Heinrich Pumpernickel |
last post by:
what does this warning mean ?
#include <stdio.h>
int main()
{
long l = 100;
printf("l is %li\n", l * 10L);
|
by: loudking |
last post by:
Hello, all
I don't quite understand what does ((time_t)-1) mean when I execute
"man 2 time"
RETURN VALUE
On success, the value of time in seconds since the Epoch is
retu
rned.
On error,...
|
by: Charles Arthur |
last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
|
by: ryjfgjl |
last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
|
by: nemocccc |
last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
|
by: Sonnysonu |
last post by:
This is the data of csv file
1 2 3
1 2 3
1 2 3
1 2 3
2 3
2 3
3
the lengths should be different i have to store the data by column-wise with in the specific length.
suppose the i have to...
|
by: Hystou |
last post by:
There are some requirements for setting up RAID:
1. The motherboard and BIOS support RAID configuration.
2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers,...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
| |