I would like to spark the discussion about the following syntax problem I
encounter.
THE PROBLEM
I have a lot times the following code:
for x in [-2, -1, 0, 1, 2, 3, 4]:
if x 0:
... more code...
It is not the addional line containing 'if x 0:' that bothers me, but the
additional indentation.
THE SOLUTION
More pythonic in view would be:
for x in [-2, -1, 0, 1, 2, 3, 4] if x 0:
... more code ...
This blends basically
[x for x in [-2, -1, 0, 1, 2, 3, 4] if x 0]
and
x = y if x 0 else 10
EXTENDING
And maybe a few usefull variants, like:
for x in [-2, -1, 0, 1, 2, 3, 4] if x 0 else -x:
... more code ...
In this case x will be 2, 1, 0, 1, 2, 3, 4. 37 2185
at wrote:
THE PROBLEM
I have a lot times the following code:
for x in [-2, -1, 0, 1, 2, 3, 4]:
if x 0:
... more code...
It is not the addional line containing 'if x 0:' that bothers me, but the
additional indentation.
for x in ...:
if not x 0:
continue
... more code ...
--
Giovanni Bajo
at wrote:
More pythonic in view would be:
for x in [-2, -1, 0, 1, 2, 3, 4] if x 0:
... more code ...
Pythonic? Do you realize that Python hasn't even adopted well-known
statements like 'switch' and 'do while' because they would be redundant?
This could be more convenient to you, but certainly not pythonic.
Cheers,
--
Roberto Bonvallet
On 2006-12-13, Roberto Bonvallet <Ro***************@cern.chwrote:
at wrote:
>More pythonic in view would be:
for x in [-2, -1, 0, 1, 2, 3, 4] if x 0: ... more code ...
Pythonic? Do you realize that Python hasn't even adopted
well-known statements like 'switch' and 'do while' because they
would be redundant?
This could be more convenient to you, but certainly not
pythonic. Cheers,
I tried it once myself. It seemed like a feasible thing that
might work in Python. It didn't annoy me that it didn't work, but
it did seem natural to me given the syntax of comprehensions.
--
Neil Cerutti
at <at@tuko.nlwrites:
I have a lot times the following code:
for x in [-2, -1, 0, 1, 2, 3, 4]:
if x 0:
... more code...
Use:
for x in (x in [-2, -1, 0, 1, 2, 3, 4] if x 0):
... more code ...
On 13 Dec 2006 07:47:23 -0800, Paul Rubin
<"http://phr.cx"@nospam.invalidwrote:
at <at@tuko.nlwrites:
I have a lot times the following code:
for x in [-2, -1, 0, 1, 2, 3, 4]:
if x 0:
... more code...
Use:
for x in (x in [-2, -1, 0, 1, 2, 3, 4] if x 0):
... more code ...
--
or filter:
from itertools import ifilter
for x in ifilter(lambda x: x 0, [-2, -1, 0, 1, 2, 3, 4]):
...more code... http://mail.python.org/mailman/listinfo/python-list
You proposal, seems nice to me but it doesn't work with Python 2.4.3, should
it work with 2.5?
Again I am just wondering if the approach for
[x for c x in some_list if some_condition]
and
x = a if b else c
could be generalized for normal straight forward iterations:
for x in some_list if some_condition:
--- etc...
I am not looking for a work around but more interest if other people might
judge this syntax would come in handy?
Interested in any feedback!
Kind regards,
@
Paul Rubin wrote:
at <at@tuko.nlwrites:
>I have a lot times the following code:
for x in [-2, -1, 0, 1, 2, 3, 4]: if x 0: ... more code...
Use:
for x in (x in [-2, -1, 0, 1, 2, 3, 4] if x 0):
... more code ...
Forget 'pythonic'.
I just need to get work done and I see this type of conditional iteration
showing up many times obscuring my code because of the additional
indentation.
In line with previous syntax improvements made in Python my proposal (or
obvious variants) seems a logical next step. Unless of course nobody
appreciates it. That's the discussion I'd like to have here in the forum.
All the best
@
Roberto Bonvallet wrote:
at wrote:
>More pythonic in view would be:
for x in [-2, -1, 0, 1, 2, 3, 4] if x 0: ... more code ...
Pythonic? Do you realize that Python hasn't even adopted well-known
statements like 'switch' and 'do while' because they would be redundant?
This could be more convenient to you, but certainly not pythonic.
Cheers,
I just need to get work done and I see this type of conditional iteration
showing up many times obscuring my code because of the additional
indentation.
Me too. When I don't like the additional indentation I usually have:
if not condition: continue
at the beginning of the block
In line with previous syntax improvements made in Python my proposal (or
obvious variants) seems a logical next step. Unless of course nobody
appreciates it. That's the discussion I'd like to have here in the forum.
Looks good to me.
--
Gabriel Genellina
The proposed solution impairs readability because there's a "surprise"
at the end. List comprehensions already open the language up to
readability abuse. Lets not add more.
To avoid the unwanted indentation, I would go with the already
suggested "if not x>0: continue" solution or else something like this:
positiveMembers = [x for x in [-2, -1, 0, 1, 2, 3, 4] if x>0]
for x in positiveMembers:
#do stuff
This has the advantage of being more self-documenting.
at wrote:
I would like to spark the discussion about the following syntax problem I
encounter.
THE PROBLEM
I have a lot times the following code:
for x in [-2, -1, 0, 1, 2, 3, 4]:
if x 0:
... more code...
It is not the addional line containing 'if x 0:' that bothers me, but the
additional indentation.
THE SOLUTION
More pythonic in view would be:
for x in [-2, -1, 0, 1, 2, 3, 4] if x 0:
... more code ...
This blends basically
[x for x in [-2, -1, 0, 1, 2, 3, 4] if x 0]
and
x = y if x 0 else 10
EXTENDING
And maybe a few usefull variants, like:
for x in [-2, -1, 0, 1, 2, 3, 4] if x 0 else -x:
... more code ...
In this case x will be 2, 1, 0, 1, 2, 3, 4.
"at" <at@tuko.nlwrote in message
news:45*********************@news.xs4all.nl...
>
More pythonic in view would be:
for x in [-2, -1, 0, 1, 2, 3, 4] if x 0:
... more code ...
Already proposed by someone and rejected by GvR.
at wrote:
I am not looking for a work around but more interest if other people might
judge this syntax would come in handy?
Of course people have expressed interest in this in the past, but it's
not going to happen. There's a way to nest for and if statements, and
a different way to nest for and if clauses in listcomps, and the two
methods are considered distinct. Although Guido has said that saving
indentation levels is important, he hasn't said anything (that I'm
aware of) that suggests it's important enough to add this complexity
and redundancy to the language. Sorry.
Carl Banks
No offense, but my conclusions from your mail is that readability is a
matter of taste.
My brains need to process a whole lot more information with your solution
than in my proposal...
but I read somewhere else that GvR rejected the proposal :-(
Ciao,
@ sh******@gmail.com wrote:
The proposed solution impairs readability because there's a "surprise"
at the end. List comprehensions already open the language up to
readability abuse. Lets not add more.
To avoid the unwanted indentation, I would go with the already
suggested "if not x>0: continue" solution or else something like this:
positiveMembers = [x for x in [-2, -1, 0, 1, 2, 3, 4] if x>0]
for x in positiveMembers:
#do stuff
This has the advantage of being more self-documenting.
at wrote:
>I would like to spark the discussion about the following syntax problem I encounter.
THE PROBLEM
I have a lot times the following code:
for x in [-2, -1, 0, 1, 2, 3, 4]: if x 0: ... more code...
It is not the addional line containing 'if x 0:' that bothers me, but the additional indentation.
THE SOLUTION
More pythonic in view would be:
for x in [-2, -1, 0, 1, 2, 3, 4] if x 0: ... more code ...
This blends basically
[x for x in [-2, -1, 0, 1, 2, 3, 4] if x 0]
and
x = y if x 0 else 10
EXTENDING
And maybe a few usefull variants, like:
for x in [-2, -1, 0, 1, 2, 3, 4] if x 0 else -x: ... more code ...
In this case x will be 2, 1, 0, 1, 2, 3, 4.
Dear Carl,
Well, all I can say that for me as a user it would make sense...
Curiosity: in what sense is it redundant?
All solution/workarounds I have seen so far involve creation of new lists
(subsets) adding to more processing/computation/memory usage. Redundant
suggests that you know alternatives that don't do that.
Does Guido ever change his mind?
Cheers,
@
Carl Banks wrote:
at wrote:
>I am not looking for a work around but more interest if other people might judge this syntax would come in handy?
Of course people have expressed interest in this in the past, but it's
not going to happen. There's a way to nest for and if statements, and
a different way to nest for and if clauses in listcomps, and the two
methods are considered distinct. Although Guido has said that saving
indentation levels is important, he hasn't said anything (that I'm
aware of) that suggests it's important enough to add this complexity
and redundancy to the language. Sorry.
Carl Banks
at wrote:
Well, all I can say that for me as a user it would make sense...
Which is, like, step one out of a hundred for getting a syntax change
into the language.
Curiosity: in what sense is it redundant?
It creates syntactical support for two different ways to do something.
If your plan were adopted, then we'd have two different spellings for
the same thing:
for i in a:
if i != 0:
use(i)
for i in a if i != 0:
use(i)
Now, redundant syntax isn't a deal breaker by itself. You have to ask
what is buys you. In this case, all it does is save you a single level
of indentation--that's it. There's no performance benefit. It doesn't
simplify logic. It doesn't make the code any more readable of clear.
It's only a minor improvement in conciseness. It hardly saves any
typing (unless you indent by hand). Even its one clear benefit, saving
indentation, is something you can already get with "if not x:
continue".
Considering how little this syntax change buys, it really doesn't make
a lot of sense for a language that places high emphasis on avoiding
redundancy.
All solution/workarounds I have seen so far involve creation of new lists
(subsets) adding to more processing/computation/memory usage. Redundant
suggests that you know alternatives that don't do that.
Does Guido ever change his mind?
Yes, but I guarantee "it makes sense for me" isn't going to convince
him. By the way, I'd suggest when posting to comp.lang.python and/or
python-list in the future, you put your replies beneath the quoted text
for the benefit of any future readers (not to mention present readers).
Carl Banks
at <at@tuko.nlwrites:
You proposal, seems nice to me but it doesn't work with Python 2.4.3, should
it work with 2.5?
Again I am just wondering if the approach for
[x for c x in some_list if some_condition]
and
x = a if b else c
could be generalized for normal straight forward iterations:
for x in some_list if some_condition:
Sorry, I got it wrong. Should have said:
for x in (x for x in some_list if some_condition):
...
So your example would have been:
for x in (x for x in [-2, -1, 0, 1, 2, 3, 4] if x 0):
... more code ...
It should work in 2.4.
at wrote:
It is not the addional line containing 'if x 0:' that bothers me, but the
additional indentation.
I don't find the additional indentation bothersome.
In fact I think it's helpful, because it makes it
obvious that there is something else going on besides
just a loop.
--
Greg
My comments below.
Kind regards,
@
Carl Banks wrote:
at wrote:
>Well, all I can say that for me as a user it would make sense...
Which is, like, step one out of a hundred for getting a syntax change
into the language.
>Curiosity: in what sense is it redundant?
It creates syntactical support for two different ways to do something.
If your plan were adopted, then we'd have two different spellings for
the same thing:
for i in a:
if i != 0:
use(i)
for i in a if i != 0:
use(i)
With the current Python syntax, I can create for every two lines of code a
dozen alternative implementations:
# example 1
a = {}
a['b'] = 'c'
versus:
a = {'b': 'c'}
# example 2
l = []
for l in some_list:
if some_condition:
l.append(l)
versus:
l = []
for x in some_list:
if some_condition:
l = l + [x]
or:
l = [x for x in some_list if some_condition]
(the beautiful one)
So your argument doesn't mean much I would say!
>
Now, redundant syntax isn't a deal breaker by itself. You have to ask
what is buys you. In this case, all it does is save you a single level
of indentation--that's it. There's no performance benefit. It doesn't
simplify logic. It doesn't make the code any more readable of clear.
It's only a minor improvement in conciseness. It hardly saves any
typing (unless you indent by hand). Even its one clear benefit, saving
indentation, is something you can already get with "if not x:
continue".
Well there is a clear performance benefit, or more precisely a productivity
benefit. And -please- do not underestimate this for a language like Python,
which has many supporters due to its perceived and high productivity and
challenged on this point by languages like Ruby.
'for x in some_list if some_condition:'
is psychological very strong, because the brain will most likely treat the
in the same way as :
for every apple in the fruitbasket take one if green
Basically upon reading this first line you know exactly to what list of
items your next section of code applies.
But again everything is a matter of taste and I assume that's why the change
control body is put into the hand of one person.
Considering how little this syntax change buys, it really doesn't make
a lot of sense for a language that places high emphasis on avoiding
redundancy.
>All solution/workarounds I have seen so far involve creation of new lists (subsets) adding to more processing/computation/memory usage. Redundant suggests that you know alternatives that don't do that.
Does Guido ever change his mind?
Yes, but I guarantee "it makes sense for me" isn't going to convince
him. By the way, I'd suggest when posting to comp.lang.python and/or
python-list in the future, you put your replies beneath the quoted text
for the benefit of any future readers (not to mention present readers).
I hope this this thread will support the "it makes sense for me" with
arguments. Again it is not my intention to fight windmills, but to see if
there are strong arguments against it on one hand and if there supporters
on the other hand.
>
Carl Banks
Thanx Paul!
Do you know if this generates a new list internally (memory consumption?)
@
Paul Rubin wrote:
at <at@tuko.nlwrites:
>You proposal, seems nice to me but it doesn't work with Python 2.4.3, should it work with 2.5?
Again I am just wondering if the approach for
[x for c x in some_list if some_condition]
and x = a if b else c
could be generalized for normal straight forward iterations:
for x in some_list if some_condition:
Sorry, I got it wrong. Should have said:
for x in (x for x in some_list if some_condition):
...
So your example would have been:
for x in (x for x in [-2, -1, 0, 1, 2, 3, 4] if x 0):
... more code ...
It should work in 2.4.
Hi Greg,
Well point is that the condition is the only thing happening and does not
really apply to the indented code section, but basically to the list used
in the indented code section.
When I read this code back its like, 'oh we use this list' and by the if
some_condition the next thing I think is 'hm, not all of the list' and even
worse should I worry if more restrictions can be found when I read
further...
All the best,
@
greg wrote:
at wrote:
>It is not the addional line containing 'if x 0:' that bothers me, but the additional indentation.
I don't find the additional indentation bothersome.
In fact I think it's helpful, because it makes it
obvious that there is something else going on besides
just a loop.
--
Greg
at <at@tuko.nlwrites:
for x in (x for x in [-2, -1, 0, 1, 2, 3, 4] if x 0):
... more code ...
Do you know if this generates a new list internally (memory consumption?)
It does not. That parenthesized expression is a called generator
expression. It compiles to a small subroutine, more or less, that
gets invoked repeatedly as you iterate through it.
A similar expression with square brackets is called a list
comprehension and does generate a new list.
at wrote:
Carl Banks wrote:
at wrote:
Well, all I can say that for me as a user it would make sense...
Which is, like, step one out of a hundred for getting a syntax change
into the language.
Curiosity: in what sense is it redundant?
It creates syntactical support for two different ways to do something.
If your plan were adopted, then we'd have two different spellings for
the same thing:
for i in a:
if i != 0:
use(i)
for i in a if i != 0:
use(i)
With the current Python syntax, I can create for every two lines of code a
dozen alternative implementations:
# example 1
a = {}
a['b'] = 'c'
versus:
a = {'b': 'c'}
# example 2
l = []
for l in some_list:
if some_condition:
l.append(l)
versus:
l = []
for x in some_list:
if some_condition:
l = l + [x]
or:
l = [x for x in some_list if some_condition]
(the beautiful one)
So your argument doesn't mean much I would say!
That's a pretty asinine and/or stupid thing for you to say, since you
took my argument completely out of context. In particular, you ignored
the following paragraph, where I weighed the benefits of the new syntax
versus the cost of redundancy.
Have you done that in your counterexamples? Did you weigh the
benefits, and somehow conclude that what different the syntaxes in the
counterexamples buy is just as little as what your proposal buys? No,
you didn't.
Next time, wait till I've actually made my argument before passing
judgment on whether it means anything.
Now, redundant syntax isn't a deal breaker by itself. You have to ask
what is buys you. In this case, all it does is save you a single level
of indentation--that's it. There's no performance benefit. It doesn't
simplify logic. It doesn't make the code any more readable of clear.
It's only a minor improvement in conciseness. It hardly saves any
typing (unless you indent by hand). Even its one clear benefit, saving
indentation, is something you can already get with "if not x:
continue".
Well there is a clear performance benefit, or more precisely a productivity
benefit.
Performance and productivity aren't the same thing. There is no
peformance benefit of your syntax. Productivity is not so clear cut.
You might be able to argue that there's some marginal productivity
benefit to using your syntax, but I can't imagine it'd be anything
substantial.
And -please- do not underestimate this for a language like Python,
which has many supporters due to its perceived and high productivity and
challenged on this point by languages like Ruby.
'for x in some_list if some_condition:'
is psychological very strong, because the brain will most likely treat the
in the same way as :
for every apple in the fruitbasket take one if green
Basically upon reading this first line you know exactly to what list of
items your next section of code applies.
I don't understand why this wouldn't also apply if the if statement
happens to be on the following line. I still think all this is is
whining about the extra indentation.
But again everything is a matter of taste and I assume that's why the change
control body is put into the hand of one person.
[snip]
Does Guido ever change his mind?
Yes, but I guarantee "it makes sense for me" isn't going to convince
him. By the way, I'd suggest when posting to comp.lang.python and/or
python-list in the future, you put your replies beneath the quoted text
for the benefit of any future readers (not to mention present readers).
I hope this this thread will support the "it makes sense for me" with
arguments. Again it is not my intention to fight windmills,
I would just stop right now, then. It's not going to change.
but to see if
there are strong arguments against it on one hand and if there supporters
on the other hand.
Carl Banks
By the way,
I think by approving
a = b if condition else c
used to avloind
if condition:
a = b
else:
a = c
which is dealing with same psychological problem, Guido also recognizes some
need...
Is it redundant according to your criteria, yes I would say:
a = {True: a, False: c}[condition]
or
a = [c, a][condition]
would yield exactly the same even in one sentence....
Cheers,
@
at wrote:
My comments below.
Kind regards,
@
Carl Banks wrote:
>at wrote:
>>Well, all I can say that for me as a user it would make sense...
Which is, like, step one out of a hundred for getting a syntax change into the language.
>>Curiosity: in what sense is it redundant?
It creates syntactical support for two different ways to do something. If your plan were adopted, then we'd have two different spellings for the same thing:
for i in a: if i != 0: use(i)
for i in a if i != 0: use(i)
With the current Python syntax, I can create for every two lines of code a
dozen alternative implementations:
# example 1
a = {}
a['b'] = 'c'
versus:
a = {'b': 'c'}
# example 2
l = []
for l in some_list:
if some_condition:
l.append(l)
versus:
l = []
for x in some_list:
if some_condition:
l = l + [x]
or:
l = [x for x in some_list if some_condition]
(the beautiful one)
So your argument doesn't mean much I would say!
>> Now, redundant syntax isn't a deal breaker by itself. You have to ask what is buys you. In this case, all it does is save you a single level of indentation--that's it. There's no performance benefit. It doesn't simplify logic. It doesn't make the code any more readable of clear. It's only a minor improvement in conciseness. It hardly saves any typing (unless you indent by hand). Even its one clear benefit, saving indentation, is something you can already get with "if not x: continue".
Well there is a clear performance benefit, or more precisely a
productivity benefit. And -please- do not underestimate this for a
language like Python, which has many supporters due to its perceived and
high productivity and challenged on this point by languages like Ruby.
'for x in some_list if some_condition:'
is psychological very strong, because the brain will most likely treat the
in the same way as :
for every apple in the fruitbasket take one if green
Basically upon reading this first line you know exactly to what list of
items your next section of code applies.
But again everything is a matter of taste and I assume that's why the
change control body is put into the hand of one person.
>Considering how little this syntax change buys, it really doesn't make a lot of sense for a language that places high emphasis on avoiding redundancy.
>>All solution/workarounds I have seen so far involve creation of new lists (subsets) adding to more processing/computation/memory usage. Redundant suggests that you know alternatives that don't do that.
Does Guido ever change his mind?
Yes, but I guarantee "it makes sense for me" isn't going to convince him. By the way, I'd suggest when posting to comp.lang.python and/or python-list in the future, you put your replies beneath the quoted text for the benefit of any future readers (not to mention present readers).
I hope this this thread will support the "it makes sense for me" with
arguments. Again it is not my intention to fight windmills, but to see if
there are strong arguments against it on one hand and if there supporters
on the other hand.
>> Carl Banks
Hi Paul,
I appreciate your explanation!
Thanx
@
Paul Rubin wrote:
at <at@tuko.nlwrites:
for x in (x for x in [-2, -1, 0, 1, 2, 3, 4] if x 0):
... more code ...
>Do you know if this generates a new list internally (memory consumption?)
It does not. That parenthesized expression is a called generator
expression. It compiles to a small subroutine, more or less, that
gets invoked repeatedly as you iterate through it.
A similar expression with square brackets is called a list
comprehension and does generate a new list.
at <at@tuko.nlwrote:
By the way,
I think by approving
a = b if condition else c
used to avloind
if condition:
a = b
else:
a = c
Neither of those is much of an improvement over the other, and in fact if
b or c are complex expressions I would definitely favour the longhand form.
The benefit of having a conditional expression though is that in some
situations it can make the code clearer by allowing you to avoid creating a
name at all. e.g. if 'a' was then used as a parameter in a function call:
d = fn(b if condition else c)
and a has disappeared entirely.
>
which is dealing with same psychological problem, Guido also
recognizes some need...
Is it redundant according to your criteria, yes I would say:
a = {True: a, False: c}[condition]
or
a = [c, a][condition]
would yield exactly the same even in one sentence....
You do realise, I hope, that neither of these last two gives the same
results as the inline 'if'?
>>x = 0 print 3/x if x != 0 else -1
-1
>>print {True: 3/x, False: -1}[x != 0]
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
print {True: 3/x, False: -1}[x != 0]
ZeroDivisionError: integer division or modulo by zero
>>print [-1, 3/x][x != 0]
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
print [-1, 3/x][x != 0]
ZeroDivisionError: integer division or modulo by zero
>>>
and before you suggest the good old standby and/or technique, that fails
for other values:
>>print x != 0 and 3/x or -1
-1
>>x=5 print x != 0 and 3/x or -1
-1
>>>
You need to use the messy:
>>print (x != 0 and (3/x,) or (-1,))[0]
0
to get exactly the same effect as the inline if with loss of both
readability and performance.
Is it redundant according to your criteria, yes I would say:
>
a = {True: a, False: c}[condition]
or
a = [c, a][condition]
would yield exactly the same even in one sentence....
Obviously it is _not_ the exact same.
def fac(n):
return n * fac(n-1) if n else 1
Try that with your recipes above.
Diez
at wrote:
I think by approving
a = b if condition else c
used to avloind
if condition:
a = b
else:
a = c
which is dealing with same psychological problem, Guido also recognizes some
need...
GvR did not introduce the new conditional syntax because he felt it was
needed or just to avoid typing a couple of extra lines. He did it just to
avoid people keep using the ugly and error-prone "a and b or c" idiom. See
the related PEP: http://www.python.org/dev/peps/pep-0308/
--
Roberto Bonvallet
at wrote:
By the way,
I think by approving
a = b if condition else c
used to avloind
if condition:
a = b
else:
a = c
which is dealing with same psychological problem, Guido also recognizes some
need...
If you think that this change was made for "psychological" reasons, you
are terribly deluded.
Carl Banks
Dear Diez,
True, I was just mentioning a workaround for a typical case.
Kind regards,
Arjan
Diez B. Roggisch wrote:
>Is it redundant according to your criteria, yes I would say:
a = {True: a, False: c}[condition]
or
a = [c, a][condition]
would yield exactly the same even in one sentence....
Obviously it is _not_ the exact same.
def fac(n):
return n * fac(n-1) if n else 1
Try that with your recipes above.
Diez
Dear Duncan,
Points taken. Its just a workaround for a specific case, I know. Maybe I
just love the elegance of
new_list = [x for x in some_list if some_cond]
and like to see it extended...
I got I nice tip on generators however which would allow me to something
similar without consuming too much additional resources.
Kind regards,
Arjan
Duncan Booth wrote:
at <at@tuko.nlwrote:
>By the way,
I think by approving
a = b if condition else c
used to avloind
if condition: a = b else: a = c
Neither of those is much of an improvement over the other, and in fact if
b or c are complex expressions I would definitely favour the longhand
form. The benefit of having a conditional expression though is that in
some situations it can make the code clearer by allowing you to avoid
creating a name at all. e.g. if 'a' was then used as a parameter in a
function call:
d = fn(b if condition else c)
and a has disappeared entirely.
>> which is dealing with same psychological problem, Guido also recognizes some need...
Is it redundant according to your criteria, yes I would say:
a = {True: a, False: c}[condition]
or
a = [c, a][condition]
would yield exactly the same even in one sentence....
You do realise, I hope, that neither of these last two gives the same
results as the inline 'if'?
>>>x = 0 print 3/x if x != 0 else -1
-1
>>>print {True: 3/x, False: -1}[x != 0]
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
print {True: 3/x, False: -1}[x != 0]
ZeroDivisionError: integer division or modulo by zero
>>>print [-1, 3/x][x != 0]
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
print [-1, 3/x][x != 0]
ZeroDivisionError: integer division or modulo by zero
>>>>
and before you suggest the good old standby and/or technique, that fails
for other values:
>>>print x != 0 and 3/x or -1
-1
>>>x=5 print x != 0 and 3/x or -1
-1
>>>>
You need to use the messy:
>>>print (x != 0 and (3/x,) or (-1,))[0]
0
to get exactly the same effect as the inline if with loss of both
readability and performance.
I am not claiming that it was THE motivation, but it solves my problem...
Carl Banks wrote:
>
at wrote:
>By the way,
I think by approving
a = b if condition else c
used to avloind
if condition: a = b else: a = c
which is dealing with same psychological problem, Guido also recognizes some need...
If you think that this change was made for "psychological" reasons, you
are terribly deluded.
Carl Banks
at wrote:
I am not claiming that it was THE motivation, but it solves my problem...
So we're back to where we started. Look, this "it makes sense for ME",
"it solves MY problem" stuff is just not going to cut it. A language
change is something everyone has to live with, therefore it has to make
sense for the community as a whole, not just one person. But you've
completely ignored concerns that don't apply to YOU this whole thread.
Carl Banks
PS. You're top-posting again. Please respect other readers.
at wrote:
I think by approving
a = b if condition else c
Again, this allows something to be written as an
expression that formerly could only be written as
a statement, which is a much bigger gain than just
crunching two statements into one.
--
Greg
at wrote:
With the current Python syntax, I can create for every two lines of code a
dozen alternative implementations:
The "one way to do it" rule seems to be widely misquoted
and misunderstood.
Of course any Turing-complete programming language is
going to provide infinitely many ways of expressing
anything.
What the "one way" rule is saying is that there is no
point in the language going out of its way to provide
two syntaxes for something with no clear reason to
prefer one or the other in any given situation. Like,
for instance, Perl having both "if (condition) statement"
and "statement if (condition)".
That's exactly the sort of thing you're proposing here,
and that's why the "one way" rule-of-thumb suggests it's
not a good idea.
It's not a hard-and-fast rule; one could argue that
list comprehensions violate it, and many people did.
Ultimately Guido decided that LCs were a big enough
win in certain situations, probably because they bring
something from the realm of statements into the realm
of expressions. Your proposal doesn't do that -- it
just rewrites a pair of statements very slightly to
give another statement, and opinions differ on whether
it would improve or hurt readability.
Furthermore, Guido has considered this exact idea
before, promoted using the same arguments, and rejected
it, so it's unlikely he would change his mind this
time around.
--
Greg
This why I prefer functional programming constructs for my
list/sequence processing needs.
------------------------------------------------------------------------
is_true = lambda x: x 0
map(process_list, filter(is_true, [-2, -1, 0, 1, 2, 3, 4]))
------------------------------------------------------------------------
at wrote:
I would like to spark the discussion about the following syntax problem I
encounter.
THE PROBLEM
I have a lot times the following code:
for x in [-2, -1, 0, 1, 2, 3, 4]:
if x 0:
... more code...
It is not the addional line containing 'if x 0:' that bothers me, but the
additional indentation.
THE SOLUTION
More pythonic in view would be:
for x in [-2, -1, 0, 1, 2, 3, 4] if x 0:
... more code ...
This blends basically
[x for x in [-2, -1, 0, 1, 2, 3, 4] if x 0]
and
x = y if x 0 else 10
EXTENDING
And maybe a few usefull variants, like:
for x in [-2, -1, 0, 1, 2, 3, 4] if x 0 else -x:
... more code ...
In this case x will be 2, 1, 0, 1, 2, 3, 4.
At Friday 15/12/2006 06:51, mystilleef wrote:
>This why I prefer functional programming constructs for my list/sequence processing needs.
------------------------------------------------------------------------ is_true = lambda x: x 0 map(process_list, filter(is_true, [-2, -1, 0, 1, 2, 3, 4])) ------------------------------------------------------------------------
Be aware that map, filter, and reduce may be dropped in Python 3000. http://www.artima.com/weblogs/viewpost.jsp?thread=98196
(and I won't miss them if gone)
--
Gabriel Genellina
Softlab SRL
__________________________________________________
Correo Yahoo!
Espacio para todos tus mensajes, antivirus y antispam ¡gratis!
¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar
In <ma***************************************@python. org>, Gabriel
Genellina wrote:
Be aware that map, filter, and reduce may be dropped in Python 3000. http://www.artima.com/weblogs/viewpost.jsp?thread=98196
(and I won't miss them if gone)
There are `imap` and `ifilter` in the `itertools` module. I guess/hope
they will stay in PythonÂ*3000. And Guido already said that ``lambda``
will stay, so maybe he changes his mind about `map` and `filter` too. :-)
Ciao,
Marc 'BlackJack' Rintsch
at wrote:
Dear Carl,
Well, all I can say that for me as a user it would make sense...
Curiosity: in what sense is it redundant?
All solution/workarounds I have seen so far involve creation of new lists
(subsets) adding to more processing/computation/memory usage. Redundant
suggests that you know alternatives that don't do that.
Does Guido ever change his mind?
Yes, he was opposed to conditional expressions at one time. I like the
scheme he came up with.
In the present context, Paul Rubin suggested new syntax:
Use:
for x in (x in [-2, -1, 0, 1, 2, 3, 4] if x 0):
... more code ...
Colin W.
>
Cheers,
@
Carl Banks wrote:
>at wrote:
>>I am not looking for a work around but more interest if other people might judge this syntax would come in handy?
Of course people have expressed interest in this in the past, but it's not going to happen. There's a way to nest for and if statements, and a different way to nest for and if clauses in listcomps, and the two methods are considered distinct. Although Guido has said that saving indentation levels is important, he hasn't said anything (that I'm aware of) that suggests it's important enough to add this complexity and redundancy to the language. Sorry.
Carl Banks
This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
by: Raymond Hettinger |
last post by:
Here is a discussion draft of a potential PEP.
The ideas grew out of the discussion on pep-284.
Comments are invited. Dart throwing is optional.
Raymond Hettinger
...
|
by: Abdullah Khaidar |
last post by:
Is there any iteration style we must use to get faster processing
time? I've tried with some style to concat number in list. But I still
don't know which one is the recommended style.
>>> def...
|
by: Benjamin Niemann |
last post by:
Hello,
I've been just investigating IE conditional comments - hiding things from
non-IE/Win browsers is easy, but I wanted to know, if it's possible to hide
code from IE/Win browsers.
I found...
|
by: Raghavendra R A V, CSS India |
last post by:
hie..
Do any one knows how to write a C program without using the
conditional statements if, for, while, do, switch, goto and even
condotional statements ? It would be a great help for me if...
|
by: jurujuba |
last post by:
Hi,
I want to write iteration- and conditional-tags with asp.net, but I
found nothing about it in books, MSDN or online-articels.
Could someone please explain me or post a link to an article...
|
by: Sathyaish |
last post by:
Can every problem that has an iterative solution also be expressed in
terms of a recursive solution?
I tried one example, and am in the process of trying out more examples,
increasing their...
|
by: Typehigh |
last post by:
I have many text fields with conditional formatting applied,
specifically when the condition is "Field Has Focus". Without any
events associated with the fields the conditional formatting works...
|
by: paulo |
last post by:
Can anyone please tell me how the C language interprets the following
code:
#include <stdio.h>
int main(void)
{
int a = 1;
int b = 10;
int x = 3;
|
by: Basilisk96 |
last post by:
This topic is difficult to describe in one subject sentence...
Has anyone come across the application of the simple statement "if
(object1's attributes meet some conditions) then (set object2's...
|
by: Charles Arthur |
last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
|
by: BarryA |
last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
|
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: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
|
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,...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new...
| |