Re: (test) ? a:b

2014-10-27 Thread ast


Mark Lawrence breamore...@yahoo.co.uk a écrit dans le message de 
news:mailman.15070.1413978605.18130.python-l...@python.org...


Also would you please access this list via https://mail.python.org/mailman/listinfo/python-list or 
read and action this https://wiki.python.org/moin/GoogleGroupsPython to prevent us seeing double 
line spacing and single line paragraphs, thanks.


Hi

I read the last document but it seems that it is intended for those who
post messages through Google Groups. I am using a usenet client so i
should not be affected

It seems that he double blank lines spacing comes from buscacio, not me

regards 


--
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-27 Thread Gregory Ewing

Michael Torrie wrote:

As far as I can tell, no BASIC dialect I've looked at (DOS and Linux
worlds only), has ever had any logical operators like AND (), OR (||),
and NOT (!).  They only appear to have bitwise operators (,|,~ C
equivalent).  The fact that comparison operators returned 0 and -1 made
the bitwise operators function the same as logical.


Applesoft used 0 and 1, so its NOT definitely wasn't bitwise
on the whole number. I can't remember what its AND and OR did
for numbers other than 0 or 1 (if I even thought to try it),
but since it did all arithmetic in floating point, I suspect
they were logical rather than bitwise.

--
Greg
--
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-26 Thread Terry Reedy

On 10/26/2014 12:15 AM, Steven D'Aprano wrote:

Ben Finney wrote:


Steven D'Aprano steve+comp.lang.pyt...@pearwood.info writes:


I suspect that Guido and the core developers disagree with you, since
they had the opportunity to fix that in Python 3 and didn't.


That doesn't follow; there are numerous warts in Python 2 that were not
fixed in Python 3. As I understand it, the preservation of bool–int
equality has more to do with preserving backward compatibility.


On reviewing PEP 285, I think it is safe to say that Guido *explicitly*
wants bools to be ints, not just for backwards compatibility:

 4) Should we strive to eliminate non-Boolean operations on bools
in the future, through suitable warnings, so that for example
True+1 would eventually (in Python 3000) be illegal?

 = No.

There's a small but vocal minority that would prefer to see
textbook bools that don't support arithmetic operations at
all, but most reviewers agree with me that bools should always
allow arithmetic operations.

http://legacy.python.org/dev/peps/pep-0285/


Thank you for digging this up.  I was one of the 'most reviewers'.

Even though filter now returns an iterator, so that one can write

sum(1 for _ in filter(None, iterable_of_bools))

without creating an unneeded itermediate list, I still prefer

sum(iterable_of_bools)

for efficiency not only for the machine but also for me writing and reading.

[snip of fine disquisition on the subject to which I have nothing to add]

--
Terry Jan Reedy


--
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-26 Thread Ben Finney
Steven D'Aprano steve+comp.lang.pyt...@pearwood.info writes:

 Do you really not see the connection between counting and summing?

Connection? Of course. But I also see a huge distinction. I'm surprised
you could misunderstand my position to the extent you think such a
question needs to be asked.

The difference between “sum these values” versus “count these values” is
important. That's at the root of why I find it confusingly wrong to sum
True or False values.

Do you really not see the distinction between counting and summing?

The question is just as silly that way.

 If you have three apples, and I have two apples, then in total we have
 (count the apples: one two three, four five) five apples.

If you have three apples in one basket, and I have two apples in one
basket, “sum the baskets” is quite a different operation from “count the
baskets”.

[3, 2]

What is the sum of those values?

How many values are there?

The distinction between those is why I find it unhelpful to express “how
many values?” with “sum them”.

 Alas, you missed the bigger bug: I'm counting *blank lines*, not
 non-blank lines. You need a `not` in there.

Which is, shall we say, not incompatible with the position that the
“count the matches by summing bools” method is an unclear expression of
intent :-)

-- 
 \ “Sittin' on the fence, that's a dangerous course / You can even |
  `\   catch a bullet from the peace-keeping force” —Dire Straits, |
_o__)   _Once Upon A Time In The West_ |
Ben Finney

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-26 Thread MRAB

On 2014-10-27 00:38, Ben Finney wrote:

Steven D'Aprano steve+comp.lang.pyt...@pearwood.info writes:


Do you really not see the connection between counting and summing?


Connection? Of course. But I also see a huge distinction. I'm surprised
you could misunderstand my position to the extent you think such a
question needs to be asked.

The difference between “sum these values” versus “count these values” is
important. That's at the root of why I find it confusingly wrong to sum
True or False values.

Do you really not see the distinction between counting and summing?

The question is just as silly that way.


If you have three apples, and I have two apples, then in total we have
(count the apples: one two three, four five) five apples.


If you have three apples in one basket, and I have two apples in one
basket, “sum the baskets” is quite a different operation from “count the
baskets”.

 [3, 2]

What is the sum of those values?

How many values are there?


Those are ints. The question is whether you can sum bools.

Python's way is to say that it's counting how many True there are.

Sometimes it's useful; pragmatism beats purity, and all that.


The distinction between those is why I find it unhelpful to express “how
many values?” with “sum them”.


Alas, you missed the bigger bug: I'm counting *blank lines*, not
non-blank lines. You need a `not` in there.


Which is, shall we say, not incompatible with the position that the
“count the matches by summing bools” method is an unclear expression of
intent :-)



--
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-26 Thread Joshua Landau
On 26 October 2014 01:03, Ben Finney ben+pyt...@benfinney.id.au wrote:
 Steven D'Aprano steve+comp.lang.pyt...@pearwood.info writes:

 I suspect that Guido and the core developers disagree with you, since
 they had the opportunity to fix that in Python 3 and didn't.

 That doesn't follow; there are numerous warts in Python 2 that were not
 fixed in Python 3. As I understand it, the preservation of bool–int
 equality has more to do with preserving backward compatibility.

Guido van Rossum answered Jul 28 '11 at 21:20,
http://stackoverflow.com/questions/3174392/is-it-pythonic-to-use-bools-as-ints
 False==0 and True==1, and there's nothing wrong with that.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-26 Thread Rustom Mody
On Sunday, October 26, 2014 9:45:22 AM UTC+5:30, Steven D'Aprano wrote:
 http://legacy.python.org/dev/peps/pep-0285/
snipped
 Ben Finney wrote:
 
 
  I agree with the decision, because this isn't an issue which often leads
  to *incorrect* code. But I maintain that it's an unfortunate and
  needlessly confusing wart of the language.
 
 That puts you in the small but vocal minority :-)

I'm sure that as the author of stats module you know of 'sampling error'!

Hint: There are two rather different populations to consider here for drawing 
the sample

- pythonistas
- textbook-istas

Analogous to another oft-seen argument -- variables.

A python variable is time-varying (like most programming languages)
A python variable is not a mathematical variable.

Historically: 1st HLL was FORTRAN which first introduced variables
in trying to come closer to math (note the name FORmula TRANslator)

Fortran's approximation was quite a good attempt for 1957.
Less and less so as people understood the consequences.
Until 1978 its creator was awarded for his creation and in his
acceptance apologized for his mistakes
-- Section 4 http://web.stanford.edu/class/cs242/readings/backus.pdf

tl;dr People make mistakes. Mistakes can be corrected


==
Of course
1. There are the logical operators and, xor
2. Put them into a certain config -- half-adder 
   https://en.wikipedia.org/wiki/Adder_%28electronics%29#Half_adder
3. [Keep reading down]. ..
   full-adder
4. Ripple-carry adder
   :
   :
5. ALU ie Arithmetic Logic Unit

IOW arithmetic/logic distinctions are fuzzy.

Distinctions are fuzzy ≠ Should not be made [In my book!]
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-26 Thread Ben Finney
Joshua Landau jos...@landau.ws writes:

 Guido van Rossum answered Jul 28 '11 at 21:20,
 http://stackoverflow.com/questions/3174392/is-it-pythonic-to-use-bools-as-ints
  False==0 and True==1, and there's nothing wrong with that.

Guido is incorrect. I've already stated what's wrong.

That's different from saying I want to change how Python behaves *now*,
of course. But to say “there's nothing wrong with that” dismisses the
problems without addressing them. Guido isn't perfect, so that's okay.

-- 
 \“Telling pious lies to trusting children is a form of abuse, |
  `\plain and simple.” —Daniel Dennett, 2010-01-12 |
_o__)  |
Ben Finney

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-26 Thread Rustom Mody
On Monday, October 27, 2014 7:59:04 AM UTC+5:30, Ben Finney wrote:
 Joshua Landau writes:
 
  Guido van Rossum answered Jul 28 '11 at 21:20,
  http://stackoverflow.com/questions/3174392/is-it-pythonic-to-use-bools-as-ints
   False==0 and True==1, and there's nothing wrong with that.
 
 Guido is incorrect. I've already stated what's wrong.
 
 That's different from saying I want to change how Python behaves *now*,
 of course. But to say there's nothing wrong with that dismisses the
 problems without addressing them. Guido isn't perfect, so that's okay.

Yes; thats my position also (here and in general).

Language changes can be (hugely) disruptive.
The cost/benefit of disruption/improvement is always to be considered

Does not mean the choices are perfect.

In particular, when introducing a beginner, its best if teachers are upfront 
about goofups. It helps everyone. Helps...

- the noob who is saved from self-flagellating Am I a fool?
- helps the python ecosystem: These guys are straightforward; dont cover
up their mistakes
- etc -- eg noob's future employer
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-26 Thread Joshua Landau
On 27 October 2014 02:28, Ben Finney ben+pyt...@benfinney.id.au wrote:
 Joshua Landau jos...@landau.ws writes:

 Guido van Rossum answered Jul 28 '11 at 21:20,
 http://stackoverflow.com/questions/3174392/is-it-pythonic-to-use-bools-as-ints
  False==0 and True==1, and there's nothing wrong with that.

 Guido is incorrect. I've already stated what's wrong.

You were arguing about what Guido thinks. I'm pretty sure Guido gets
first say in that, regardless of whether anyone agrees with him.

Regardless, I feel you're making this out as a black and white issue.
Guido isn't incorrect, he just has a different opinion. Designing a
language and calling things wrong or right gets you Haskell. You
can discuss the advantages of each approach without drawing lines in
the sand. Although if you do want a language like Haskell, there are a
few great choices to chose from.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-26 Thread Ben Finney
Joshua Landau jos...@landau.ws writes:

 On 27 October 2014 02:28, Ben Finney ben+pyt...@benfinney.id.au wrote:
  Guido is incorrect. I've already stated what's wrong.

 You were arguing about what Guido thinks.

I don't know where I did that; to my knowledge, this is the first time
I've mentioned Guido, and it's in rebuttal to his authority on the issue
of whether “there's nothing wrong with” bool-as-a-special-int.

(On the separate issue of whether Guido is an authority on how Python
will behave, I haven't even commented. To be clear: yes, he is the BDFL
and therefore is authoritative on that issue.)

 Regardless, I feel you're making this out as a black and white issue.

There either is something problematic with a behaviour, or there isn't.

The *degree* of wrongness can vary. I'm merely pointing out that, in
this case, it's non-zero.

-- 
 \ “I must say that I find television very educational. The minute |
  `\   somebody turns it on, I go to the library and read a book.” |
_o__)—Groucho Marx |
Ben Finney

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-25 Thread Ned Batchelder

On 10/25/14 1:03 AM, Steven D'Aprano wrote:

alister wrote:


On Fri, 24 Oct 2014 10:20:30 -0700, Dan Stromberg wrote:


On Fri, Oct 24, 2014 at 1:38 AM, Steven D'Aprano
steve+comp.lang.pyt...@pearwood.info  wrote:

I don't get why that's considered hard to read.



So why is it hard to read when the index is a flag?

value = [f, g][cond]()



[Dan]

It's clear to you, it's clear to me, but is it clear to everyone?  I
very much doubt it.

Of course it won't be clear to*everyone*  but it should be clear enough to
people who are familiar with standard Python idioms. A concrete example
should be more obvious than the fake example:

title = ('Mr', 'Ms')[person.sex == 'F']

which should be clear to anyone who understands indexing in Python and that
True == 1 and False == 0.


You mention standard Python idioms.  I think this style of 
conditional-via-indexing is becoming quite uncommon, and is no longer 
one of the standard Python idioms.  This is now in the category of 
outdated hack.


Yes, its meaning is well-defined by the language.  But no, its meaning 
is not immediately apparent to most of today's Python programmers.


Of course, opinions obviously differ.

--
Ned Batchelder, http://nedbatchelder.com

--
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-25 Thread Ian Kelly
On Sat, Oct 25, 2014 at 5:58 AM, Ned Batchelder n...@nedbatchelder.com wrote:
 You mention standard Python idioms.  I think this style of
 conditional-via-indexing is becoming quite uncommon, and is no longer one of
 the standard Python idioms.  This is now in the category of outdated hack.

I think that's probably true. And even in code written for versions of
Python than predate the ternary, I think I've seen the idiom (cond
and [if_true] or [if_false])[0] more often than the one being
discussed -- perhaps because it more closely resembles the format of
the C ternary
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-25 Thread alister
On Sat, 25 Oct 2014 16:03:16 +1100, Steven D'Aprano wrote:

 [Alister]
 I had to mentally step through this before it became apparent what it
 was doing,  can see places where it could be usefull (a switch
 replacement) but it is not instantly obvious
 
 Very little code is instantly obvious. Even when you know what the
 syntax means, you still have to understand the semantics, and sometimes
 that's far from obvious.
 
 
 a = value if condition else another Value
 
 is instantly obvious (at least to a native English speaker anyway)
 
 Ha! And yet people have, and continue to, complain *bitterly* about the
 non-standard ordering of Python's ternary if, compared to C, standard
 if...else syntax, and English.

Not Me, I don't program i C  I don't want to it is too low level fro my 
liking ( I used to program in assembler for a living)


-- 
You need tender loving care once a week - so that I can slap you into 
shape.
- Ellyn Mustard
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-25 Thread Ben Finney
Steven D'Aprano steve+comp.lang.pyt...@pearwood.info writes:

 Of course it won't be clear to *everyone* but it should be clear
 enough to people who are familiar with standard Python idioms. A
 concrete example should be more obvious than the fake example:

 title = ('Mr', 'Ms')[person.sex == 'F']

 which should be clear to anyone who understands indexing in Python and
 that True == 1 and False == 0.

I consider it an accident of history, and one which should not be
necessary to understand Python code.

In other words, I consider code which exploits the equality of True with
1, or False with 0, is code with a leaky abstraction and should be
fixed.

 Although that's probably better written as a dict lookup:

 title = {'M': 'Mr', 'F': 'Ms'}[person.sex]

 which is then more easily extended to support intersex and
 non-traditional[1] gender identities.

It's true that gender is not a binary, but even if it were, this would
be a bad idea.

A schema which blurs the distinction between boolean versus integer is a
code smell: it speaks to the high likelihood that the “flag” really
represents an entity which will soon have more than two states, and
should never have been represented as a boolean.

-- 
 \ “As scarce as truth is, the supply has always been in excess of |
  `\   the demand.” —Josh Billings |
_o__)  |
Ben Finney

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-25 Thread Dan Stromberg
On Sat, Oct 25, 2014 at 1:45 PM, Ben Finney ben+pyt...@benfinney.id.au wrote:
 Steven D'Aprano steve+comp.lang.pyt...@pearwood.info writes:
 title = ('Mr', 'Ms')[person.sex == 'F']

 which should be clear to anyone who understands indexing in Python and
 that True == 1 and False == 0.

 I consider it an accident of history, and one which should not be
 necessary to understand Python code.

 In other words, I consider code which exploits the equality of True with
 1, or False with 0, is code with a leaky abstraction and should be
 fixed.

I don't like the (a, b)[True] thing, but I use the fact that True is 1
and False is 0 sometimes.

EG, if I have 3 mutually exclusive command line options, I'll do something like:

if option_a + option_b + option_c != 1:
   sys.stderr.write('{}: -a, -b and -c are mutually
exclusive\n'.format(sys.argv[0]))
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-25 Thread Ben Finney
Dan Stromberg drsali...@gmail.com writes:

 EG, if I have 3 mutually exclusive command line options, I'll do
 something like:

 if option_a + option_b + option_c != 1:
sys.stderr.write('{}: -a, -b and -c are mutually 
 exclusive\n'.format(sys.argv[0]))

That is an excellent illustration of why exploiting this accidental
property of True and False leads to obfuscated code. The above test
gives me no clue that we're operating on boolean values, nor that we're
testing for exclusive options.

The error message bears no obvious relation to the test, and if I was
tracking down that error message I'd have no hint from the code why the
test is written that way. An explanatory comment would be needed, but
that's a strong sign IMO that instead the test should be re-written to
be much more obvious.

-- 
 \   “Never express yourself more clearly than you are able to |
  `\   think.” —Niels Bohr |
_o__)  |
Ben Finney

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-25 Thread Chris Angelico
On Sun, Oct 26, 2014 at 10:53 AM, Ben Finney ben+pyt...@benfinney.id.au wrote:
 Dan Stromberg drsali...@gmail.com writes:

 EG, if I have 3 mutually exclusive command line options, I'll do
 something like:

 if option_a + option_b + option_c != 1:
sys.stderr.write('{}: -a, -b and -c are mutually 
 exclusive\n'.format(sys.argv[0]))

 That is an excellent illustration of why exploiting this accidental
 property of True and False leads to obfuscated code. The above test
 gives me no clue that we're operating on boolean values, nor that we're
 testing for exclusive options.

Would it be more readable thus?

if len([opt for opt in (option_a, option_b, option_c) if opt]) != 1:

Because that's what it's doing. I think treating bools as numbers is
fine. Matter of opinion I guess.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-25 Thread Mark Lawrence

On 26/10/2014 01:01, Chris Angelico wrote:

On Sun, Oct 26, 2014 at 10:53 AM, Ben Finney ben+pyt...@benfinney.id.au wrote:

Dan Stromberg drsali...@gmail.com writes:


EG, if I have 3 mutually exclusive command line options, I'll do
something like:

if option_a + option_b + option_c != 1:
sys.stderr.write('{}: -a, -b and -c are mutually 
exclusive\n'.format(sys.argv[0]))


That is an excellent illustration of why exploiting this accidental
property of True and False leads to obfuscated code. The above test
gives me no clue that we're operating on boolean values, nor that we're
testing for exclusive options.


Would it be more readable thus?

if len([opt for opt in (option_a, option_b, option_c) if opt]) != 1:

Because that's what it's doing. I think treating bools as numbers is
fine. Matter of opinion I guess.

ChrisA



Horrible IMHO, it just doesn't fit in my mind set.  Still each to their own.

--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

--
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-25 Thread Chris Angelico
On Sun, Oct 26, 2014 at 11:09 AM, Mark Lawrence breamore...@yahoo.co.uk wrote:
 Horrible IMHO, it just doesn't fit in my mind set.  Still each to their own.

Yeah, the comprehension version is way more explicit (though it
probably ought to be a set and a set comp, not a tuple and a list
comp), and not as good, IMO. But it explains and justifies the
original.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-25 Thread Steven D'Aprano
Ben Finney wrote:

 Steven D'Aprano steve+comp.lang.pyt...@pearwood.info writes:
 
 Of course it won't be clear to *everyone* but it should be clear
 enough to people who are familiar with standard Python idioms. A
 concrete example should be more obvious than the fake example:

 title = ('Mr', 'Ms')[person.sex == 'F']

 which should be clear to anyone who understands indexing in Python and
 that True == 1 and False == 0.
 
 I consider it an accident of history, and one which should not be
 necessary to understand Python code.
 
 In other words, I consider code which exploits the equality of True with
 1, or False with 0, is code with a leaky abstraction and should be
 fixed.

I suspect that Guido and the core developers disagree with you, since they
had the opportunity to fix that in Python 3 and didn't.

Equating True with 1 and False with 0 is fundamental to many programming
languages, but more importantly Boolean Algebra itself normally identifies
True with 1 and False with 0. 

https://en.wikipedia.org/wiki/Boolean_algebra
http://mathworld.wolfram.com/BooleanAlgebra.html

Admittedly this is only a convention, and you're welcome to invent your own
convention, but when doing so you should be aware that Python's convention
is mathematically sound and, well, conventional.

One example of where treating True and False as 1 and 0 is useful is that it
makes counting operations very simple, e.g. counting the number of blank
lines:

sum(not line.strip() for line in lines)

If you reject implicit or explicit bool-to-int conversions:

sum(1 if not line.strip() else 0 for line in lines)

or for compatibility with Python 2.4:

sum({'': 0}.get(line.strip(), 1) for line in lines)

which I consider far less obvious than the straightforward summation of True
values. Sometimes making things *too* abstract is worse than allowing an
abstraction to leak.


-- 
Steven

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-25 Thread Ben Finney
Steven D'Aprano steve+comp.lang.pyt...@pearwood.info writes:

 I suspect that Guido and the core developers disagree with you, since
 they had the opportunity to fix that in Python 3 and didn't.

That doesn't follow; there are numerous warts in Python 2 that were not
fixed in Python 3. As I understand it, the preservation of bool–int
equality has more to do with preserving backward compatibility.

I agree with the decision, because this isn't an issue which often leads
to *incorrect* code. But I maintain that it's an unfortunate and
needlessly confusing wart of the language.

 One example of where treating True and False as 1 and 0 is useful is
 that it makes counting operations very simple, e.g. counting the
 number of blank lines:

 sum(not line.strip() for line in lines)
 sum(1 if not line.strip() else 0 for line in lines)
 sum({'': 0}.get(line.strip(), 1) for line in lines)

These all look ludicrous and explain nothing about intent, to my
reading. The ‘bool’ type exists precisely because there is a concept to
be represented which is distinct from integers.

Using a sum on non-numeric values just cracks the abstraction open
needlessly. Once I figure out what is going on, I'm left wondering why
the coder chose something so obfuscatory to their intent.

This is short and clear and needs no leaking of the underlying bool
implementation::

len(True for line in lines if line.strip())

 which I consider far less obvious than the straightforward summation
 of True values.

Why sum them at all? You aren't interested in them as numbers, you're
just asking how many objects meet a criterion. That calls not for ‘sum’,
but ‘len’. There's no need to rely on an underlying ‘int’ operation just
to count objects.

The fact that summing them gives the same answer as simply asking how
many there are, demonstrates that nothing is gained by peeking into the
implementation. The example I give above works exactly as well with no
‘int’ underlying the ‘bool’ type at all.

-- 
 \  “The way to build large Python applications is to componentize |
  `\ and loosely-couple the hell out of everything.” —Aahz |
_o__)  |
Ben Finney

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-25 Thread Michael Torrie
On 10/22/2014 09:46 PM, Gregory Ewing wrote:
 Chris Angelico wrote:
 I've seen much MUCH worse... where multiple conditional
 expressions get combined arithmetically, and then the result used
 somewhere...
 
 In the days of old-school BASIC it was common to
 exploit the fact that boolean expressions evaluated
 to 0 or 1 (or -1, depending on your dialect :) to
 achieve conditional expressions or other tricks.

As far as I can tell, no BASIC dialect I've looked at (DOS and Linux
worlds only), has ever had any logical operators like AND (), OR (||),
and NOT (!).  They only appear to have bitwise operators (,|,~ C
equivalent).  The fact that comparison operators returned 0 and -1 made
the bitwise operators function the same as logical.  But you can run
into trouble if you tried to use a common python idiom like this:

x = read_some_lines() 'returns number of lines read, or zero if none are
if not x:
print (I couldn't read any lines)
exit(1)

Basically any value other than -1 for x would cause the not x to be
true.  Off topic, and no matter to python programmers.  But for BASIC
you need to watch out for this.  One BASIC dialect introduced a set of
functions, istrue() and isfalse() to convert a non-zero truth value to
-1, and any falsish value to zero (like maybe an empty string).  That
way the bitwise operators would always function as logical operators in
a conditional expression.


-- 
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-25 Thread Ben Finney
Ben Finney ben+pyt...@benfinney.id.au writes:

 This is short and clear and needs no leaking of the underlying bool
 implementation::

 len(True for line in lines if line.strip())

Correction::

len([True for line in lines if line.strip()])

-- 
 \ “Our task must be to free ourselves from our prison by widening |
  `\our circle of compassion to embrace all humanity and the whole |
_o__)   of nature in its beauty.” —Albert Einstein |
Ben Finney

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-25 Thread Chris Angelico
On Sun, Oct 26, 2014 at 12:04 PM, Michael Torrie torr...@gmail.com wrote:
 But you can run
 into trouble if you tried to use a common python idiom like this:

 x = read_some_lines() 'returns number of lines read, or zero if none are
 if not x:
 print (I couldn't read any lines)
 exit(1)

 Basically any value other than -1 for x would cause the not x to be
 true.

So don't use Python idioms in BASIC. :) Back when I used to write
BASIC code, I'd do explicit comparisons with zero for this sort of
thing... these days, I'd use Python idioms, but I'd also write Python
code :)

I think it's indicative that the BASIC code I'm most proud of was
consciously getting around language limitations (I wrote a mess of
code in assembly language and Q-BASIC to allow my programs to use the
mouse), but the Python code I'm most proud of is using the language's
strengths.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-25 Thread Michael Torrie
On 10/25/2014 07:20 PM, Chris Angelico wrote:
 So don't use Python idioms in BASIC. :) Back when I used to write
 BASIC code, I'd do explicit comparisons with zero for this sort of
 thing... these days, I'd use Python idioms, but I'd also write Python
 code :)
 
 I think it's indicative that the BASIC code I'm most proud of was
 consciously getting around language limitations (I wrote a mess of
 code in assembly language and Q-BASIC to allow my programs to use the
 mouse), but the Python code I'm most proud of is using the language's
 strengths.

Hey I did the same thing in Turbo and then later Power BASIC.

I have a soft spot for BASIC, and now with FreeBASIC releasing their 1.0
release (object-oriented capabilities and the works), I revisited a bit
of my BASIC past.  Translated a few programs from Turbo and Power BASIC
into the more modern FreeBASIC dialect.  But now that that's done, it's
back to Python, where I'm going to stay!  Python reminds me of the best
BASIC had to offer plus a whole lot more.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-25 Thread Steven D'Aprano
Ben Finney wrote:

 Steven D'Aprano steve+comp.lang.pyt...@pearwood.info writes:
 
 I suspect that Guido and the core developers disagree with you, since
 they had the opportunity to fix that in Python 3 and didn't.
 
 That doesn't follow; there are numerous warts in Python 2 that were not 
 fixed in Python 3. As I understand it, the preservation of bool–int
 equality has more to do with preserving backward compatibility.

On reviewing PEP 285, I think it is safe to say that Guido *explicitly*
wants bools to be ints, not just for backwards compatibility:

4) Should we strive to eliminate non-Boolean operations on bools
   in the future, through suitable warnings, so that for example
   True+1 would eventually (in Python 3000) be illegal?

= No.

   There's a small but vocal minority that would prefer to see
   textbook bools that don't support arithmetic operations at
   all, but most reviewers agree with me that bools should always
   allow arithmetic operations.

http://legacy.python.org/dev/peps/pep-0285/


 I agree with the decision, because this isn't an issue which often leads
 to *incorrect* code. But I maintain that it's an unfortunate and
 needlessly confusing wart of the language.

That puts you in the small but vocal minority :-)


 One example of where treating True and False as 1 and 0 is useful is
 that it makes counting operations very simple, e.g. counting the
 number of blank lines:

 sum(not line.strip() for line in lines)
 sum(1 if not line.strip() else 0 for line in lines)
 sum({'': 0}.get(line.strip(), 1) for line in lines)
 
 These all look ludicrous and explain nothing about intent, to my
 reading.
[...]
 I'm left wondering why
 the coder chose something so obfuscatory to their intent.

Ludicrous and obfuscatory. They're awfully strong words.

Do you really not see the connection between counting and summing? If so,
that would put you in a truly small minority. The connection between adding
and counting has been known to Western mathematics since at least the
ancient Greeks, if not even earlier, and we teach it to school children. If
you have three apples, and I have two apples, then in total we have (count
the apples: one two three, four five) five apples. Pre-schoolers learn
this. I'm sure it's not too difficult for programmers.


 This is short and clear and needs no leaking of the underlying bool
 implementation::
 
 len(True for line in lines if line.strip())

I see that in a later email you discovered your unfortunate bug in this, and
corrected it to this:

len([True for line in lines if line.strip()])

Alas, you missed the bigger bug: I'm counting *blank lines*, not non-blank
lines. You need a `not` in there.

You mentioned intent before. I wonder what your intention is, to needlessly
build a potentially gigantic list of identical values, only to then throw
the list away. Could be worse; you might have written

[True for line in lines if not line.strip()].count(True)

Since the list items exist only to be counted, the actual item used makes no
difference. You could use any value at all, or even a different value each
time:

len([random.random() for line in lines if not line.strip()])

What is your reason for the choice of True as the tally marker? It doesn't
clarify your intent, or make it more obvious that you're counting the
number of non-empty lines. If you wanted to suggest a tally:

len(['/' for line in lines if not line.strip()])

at least looks like a tally:  makes four. Using a bool doesn't make this
any clearer, and you don't even have the excuse that it's efficient,
because it isn't.

Let's get rid of the list comp and write a straightforward translation:

temp = []
for line in lines:
if not line.strip():
temp.append(True)
result = len(temp)
del temp


I don't consider that sensible code at all. Why waste time building the
temporary list when all we want is a counter?

result = 0
for line in lines:
if not line.strip():
result += 1


which can be simplified to:

result = 0
for line in lines:
result += not line.strip()


I agree with you that this breaks the abstraction bools are abstract
enumerations, not ints, but that abstraction is not part of Python. If I
objected to code like this:

types = [int, str, list, dict]
for t in types:
do_something_with(t)

on the basis that we shouldn't treat types as values, because that breaks
the abstraction that types are not values, they're a different kind of
thing known only to the compiler (as in Java), I expect that you would
have no hesitation in telling me that my objection was invalid. Making
types be non-values may, or may not, be a reasonable programming model, but
it's not Python's programming model. In Python, types are themselves
objects and first-class values. Objecting to Python code because it
violates a norm from some other language is, frankly, silly.

The abstraction bools are abstract enumerations different from 

Re: (test) ? a:b

2014-10-25 Thread Chris Angelico
On Sun, Oct 26, 2014 at 3:15 PM, Steven D'Aprano
steve+comp.lang.pyt...@pearwood.info wrote:
 Since the list items exist only to be counted, the actual item used makes no
 difference. You could use any value at all, or even a different value each
 time:

 len([random.random() for line in lines if not line.strip()])

 What is your reason for the choice of True as the tally marker? It doesn't
 clarify your intent, or make it more obvious that you're counting the
 number of non-empty lines.

Personally, I'd use the original value. When you're counting
something, it's common to count that thing, rather than some stand-in.

len([line for line in lines if not line.strip()])

But that's no better than anything else. The only significance is that
it feels more like counting a filtered portion of the list.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-24 Thread ast



48K? Luxury!


ZX81 had an option for 64K
--
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-24 Thread Steven D'Aprano
Marko Rauhamaa wrote:

 BartC b...@freeuk.com:
 
 Ah, but what would

 x = [f, g][cond]()

 produce?

 It will select f or g (which should refer to functions), and call one of
 those depending on cond. That's not a problem.

 The problem is it will still evaluate both f and g,
 
 That's not really the problem. The problem is in readability.


I don't get why that's considered hard to read. We write things like this
all the time:

item = somelist[index]
value = data[key]

Presumably people won't have a problem with:

values = [f(), g(), h()]
value = values[index]

(If they do, they're going to have a bad time with Python.) They probably
won't even mind if we skip the temporary variable:

value = [f(), g(), h()][index]

and if they're experienced with languages that treat functions as
first-class values, they'll be fine with factoring out the function call:

value = [f, g, h][index]()


So why is it hard to read when the index is a flag?

value = [f, g][cond]()


Of course one can write hard-to-read code using any idiom by sheer weight of
complexity or obfuscated naming:

value = [some_function(arg)[23]['key'] or 
 another_function.method((x + y)/(z-x**(y-4)))*
 some_list[get_index(a)].spam(eggs=False, tomato='yum'),
 something.do_this(p|q).get(alpha, beta) ^
 aardvark.bobble(string%s % carrot.gamma(rs)*
 (this  that).fetch(83, 36, when=when or now)
 ][cond or flag or foo(42)-1  17 or bar(b)  thingy(c) or not d]


but re-writing that using ternary if operator won't help one iota. I don't
see why `[a, b][flag]` is inherently less readable than `b if flag else a`.



-- 
Steven

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-24 Thread Chris Angelico
On Fri, Oct 24, 2014 at 7:38 PM, Steven D'Aprano
steve+comp.lang.pyt...@pearwood.info wrote:
 Of course one can write hard-to-read code using any idiom by sheer weight of
 complexity or obfuscated naming:

 value = [some_function(arg)[23]['key'] or
  another_function.method((x + y)/(z-x**(y-4)))*
  some_list[get_index(a)].spam(eggs=False, tomato='yum'),
  something.do_this(p|q).get(alpha, beta) ^
  aardvark.bobble(string%s % carrot.gamma(rs)*
  (this  that).fetch(83, 36, when=when or now)
  ][cond or flag or foo(42)-1  17 or bar(b)  thingy(c) or not d]


I can see where your problem is. It is a cardinal error in readability
to have (x + y) followed by z-x. No wonder it's hard to read.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-24 Thread Marko Rauhamaa
Steven D'Aprano steve+comp.lang.pyt...@pearwood.info:

 So why is it hard to read when the index is a flag?

 value = [f, g][cond]()

So, subjectively, which syntax would you prefer:

if j  10:
j += 1
else:
j = 3

or:

j = j + 1 if j  10 else 3

or:

j = (lambda: 3, lambda: j + 1)[j  10]()


Marko
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-24 Thread Steven D'Aprano
Marko Rauhamaa wrote:

 Steven D'Aprano steve+comp.lang.pyt...@pearwood.info:
 
 So why is it hard to read when the index is a flag?

 value = [f, g][cond]()
 
 So, subjectively, which syntax would you prefer:

Depends on what else the code is doing. But my personal preference is a red
herring: you didn't say that you liked or preferred one version over
the other, you said that the problem with the [f, g][cond] idiom is
readability, implying that it is hard to read. I'm not asking for your
personal preference, I'm asking for justification for your suggestion that
it is hard to read.


 if j  10:
 j += 1
 else:
 j = 3
 
 or:
 
 j = j + 1 if j  10 else 3
 
 or:
 
 j = (lambda: 3, lambda: j + 1)[j  10]()

Certainly not the third one. That's needlessly obfuscated for the sake of
premature optimization. This version is much better, and probably not only
simpler and easier to read but probably more efficient too:

j = (3, j + 1)[j  10]



-- 
Steven

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-24 Thread Dan Stromberg
On Fri, Oct 24, 2014 at 1:38 AM, Steven D'Aprano
steve+comp.lang.pyt...@pearwood.info wrote:
 I don't get why that's considered hard to read.

 So why is it hard to read when the index is a flag?

 value = [f, g][cond]()

It's clear to you, it's clear to me, but is it clear to everyone?  I
very much doubt it.

Also, you've gone to the trouble of def'ing two functions here - you
may as well do a function for the if/else.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-24 Thread Tobiah

On 10/22/2014 01:29 AM, ast wrote:

Hello

Is there in Python something like:

j = (j = 10) ? 3 : j+1;

as in C language ?

thx



Out of all of the replies, I don't think anyone
actually offered the answer:


a if condition else b



--
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-24 Thread Chris Angelico
On Sat, Oct 25, 2014 at 4:23 AM, Tobiah t...@tobiah.org wrote:
 Out of all of the replies, I don't think anyone
 actually offered the answer:


 a if condition else b

Jean-Michel did, the very first response.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-24 Thread Ian Kelly
On Fri, Oct 24, 2014 at 7:07 AM, Steven D'Aprano
steve+comp.lang.pyt...@pearwood.info  if j  10:
 j += 1
 else:
 j = 3

 or:

 j = j + 1 if j  10 else 3

 or:

 j = (lambda: 3, lambda: j + 1)[j  10]()

 Certainly not the third one. That's needlessly obfuscated for the sake of
 premature optimization. This version is much better, and probably not only
 simpler and easier to read but probably more efficient too:

 j = (3, j + 1)[j  10]

Yes, the lambda approach falls victim to function calls being slow.

$ python3 -m timeit -s j = 5 if j  10: j+=1
 else: j=3
1000 loops, best of 3: 0.0513 usec per loop
$ python3 -m timeit -s j = 5 j = j + 1 if j  10 else 3
1000 loops, best of 3: 0.0519 usec per loop
$ python3 -m timeit -s j = 5 j = (3, j+1)[j  10]
1000 loops, best of 3: 0.0883 usec per loop
$ python3 -m timeit -s j = 5 j = (lambda: 3, lambda: j+1)[j  10]()
100 loops, best of 3: 0.312 usec per loop
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-24 Thread Tobiah

On 10/24/2014 10:27 AM, Chris Angelico wrote:

On Sat, Oct 25, 2014 at 4:23 AM, Tobiah t...@tobiah.org wrote:

Out of all of the replies, I don't think anyone
actually offered the answer:


 a if condition else b


Jean-Michel did, the very first response.

ChrisA




I had to search for it.  For some reason Thunderbird
didn't thread that message with all the others.


--
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-24 Thread Marko Rauhamaa
Ian Kelly ian.g.ke...@gmail.com:

 j = (lambda: 3, lambda: j + 1)[j  10]()

 Yes, the lambda approach falls victim to function calls being slow.

That's just a deficiency in the compiler. There's nothing there that
prevents the optimizer from translating the expression into the
equivalent if statement.

At any rate, the only issue at hand is the obviousness of the idiom. You
should generally choose the syntax that best expresses the logic of the
program.


Marko
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-24 Thread alister
On Fri, 24 Oct 2014 10:20:30 -0700, Dan Stromberg wrote:

 On Fri, Oct 24, 2014 at 1:38 AM, Steven D'Aprano
 steve+comp.lang.pyt...@pearwood.info wrote:
 I don't get why that's considered hard to read.
 
 So why is it hard to read when the index is a flag?

 value = [f, g][cond]()
 
 It's clear to you, it's clear to me, but is it clear to everyone?  I
 very much doubt it.

I had to mentally step through this before it became apparent what it was 
doing,  can see places where it could be usefull (a switch replacement) 
but it is not instantly obvious

a = value if condition else another Value

is instantly obvious (at least to a native English speaker anyway)
 
 Also, you've gone to the trouble of def'ing two functions here - you may
 as well do a function for the if/else.





-- 
Humor is a drug which it's the fashion to abuse.
-- William Gilbert
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-24 Thread Marko Rauhamaa
alister alister.nospam.w...@ntlworld.com:

 a = value if condition else another Value

 is instantly obvious (at least to a native English speaker anyway)

And you can go further down that road. For example, you could say things
like:

die unless everything is OK


Marko
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-24 Thread Steven D'Aprano
alister wrote:

 On Fri, 24 Oct 2014 10:20:30 -0700, Dan Stromberg wrote:
 
 On Fri, Oct 24, 2014 at 1:38 AM, Steven D'Aprano
 steve+comp.lang.pyt...@pearwood.info wrote:
 I don't get why that's considered hard to read.
 
 So why is it hard to read when the index is a flag?

 value = [f, g][cond]()
 
[Dan]
 It's clear to you, it's clear to me, but is it clear to everyone?  I
 very much doubt it.

Of course it won't be clear to *everyone* but it should be clear enough to
people who are familiar with standard Python idioms. A concrete example
should be more obvious than the fake example:

title = ('Mr', 'Ms')[person.sex == 'F']

which should be clear to anyone who understands indexing in Python and that
True == 1 and False == 0.

Although that's probably better written as a dict lookup:

title = {'M': 'Mr', 'F': 'Ms'}[person.sex]

which is then more easily extended to support intersex and
non-traditional[1] gender identities. Better still is to allow the
individual to choose their own title (Dr, Prof, Mrs, Miss, Mx, Sir, Dame,
etc.) rather than calculate it from their sex, but that's moving away from
the point I am making that this idiom isn't some weird and hackish
bizarrity. We use list indexing and key lookup all the time, this is just a
special case of the same. It's no more hackish than:

mapping = {True: something which is factual,
   False: something which people prefer to believe}
value = mapping[flag]


[Alister]
 I had to mentally step through this before it became apparent what it was
 doing,  can see places where it could be usefull (a switch replacement)
 but it is not instantly obvious

Very little code is instantly obvious. Even when you know what the syntax
means, you still have to understand the semantics, and sometimes that's far
from obvious.


 a = value if condition else another Value
 
 is instantly obvious (at least to a native English speaker anyway)

Ha! And yet people have, and continue to, complain *bitterly* about the
non-standard ordering of Python's ternary if, compared to C, standard
if...else syntax, and English.

If the syntax is like C, then people will use it, or else they will
complain that the syntax is incomprehensible.

Personally, I don't accept or agree with such complaints. Python's ternary
if follows the same syntax as this English variant:

People will use it if the syntax is like C, or else they will complain that
the syntax is incomprehensible.

Still, English-like though it is, Python's ternary if does violate the
expectations of those who expect the condition to come first, as the
standard if...else block does.


[Dan]
 Also, you've gone to the trouble of def'ing two functions here - you may
 as well do a function for the if/else.

Not every one-liner expression needs to go into a function.




[1] For Western Christian definitions of traditional. Other cultures have
traditionally recognised more than just a binary state of gender and
sexuality, e.g. https://en.wikipedia.org/wiki/Hijra_%28South_Asia%29

-- 
Steven

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-24 Thread Chris Angelico
On Sat, Oct 25, 2014 at 4:03 PM, Steven D'Aprano
steve+comp.lang.pyt...@pearwood.info wrote:
 Ha! And yet people have, and continue to, complain *bitterly* about the
 non-standard ordering of Python's ternary if, compared to C, standard
 if...else syntax, and English.

 If the syntax is like C, then people will use it, or else they will
 complain that the syntax is incomprehensible.

 Personally, I don't accept or agree with such complaints. Python's ternary
 if follows the same syntax as this English variant:

 People will use it if the syntax is like C, or else they will complain that
 the syntax is incomprehensible.

Partly, I think this is a difference between programming and pure
mathematics. In algebra, there's operator precedence, but no order of
evaluation; in programming, there's both:

https://docs.python.org/3/reference/expressions.html#evaluation-order

In English, there's not really a concept of order of evaluation
either. People will use it doesn't need to be evaluated separately
from if the syntax is like C. But in Python, the if/else operator
mucks up the general principle that an expression will be evaluated
left-to-right, because it's evaluated middle-to-outer for that one
operator. Messing with internal expectations, even if it's following
some external logic like English grammar, will confuse people.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-23 Thread MRAB

On 2014-10-23 04:46, Gregory Ewing wrote:

Chris Angelico wrote:

I've seen much MUCH worse... where multiple conditional
expressions get combined arithmetically, and then the result used
somewhere...


In the days of old-school BASIC it was common to
exploit the fact that boolean expressions evaluated
to 0 or 1 (or -1, depending on your dialect :) to
achieve conditional expressions or other tricks.

Probably forgiveable, given that there were no real
conditional expressions, and every byte of your 48K
or less of RAM was precious...


48K? Luxury!
--
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-23 Thread BartC
Dennis Lee Bieber wlfr...@ix.netcom.com wrote in message 
news:mailman.15097.1414022143.18130.python-l...@python.org...

On Wed, 22 Oct 2014 19:08:40 +0100, BartC b...@freeuk.com declaimed the
following:



Comparing:

x = cond ? f() : g();   # C version

with

x = [f(), g()] [cond]


(Should probably be x = [g(), f()] [cond])



the latter evaluates both f() and g() instead of just one. Apart from 
being

inefficient, it can have unintended side-effects.


Ah, but what would

x = [f, g][cond]()

produce?


It will select f or g (which should refer to functions), and call one of 
those depending on cond. That's not a problem.


The problem is it will still evaluate both f and g, even if they are simple 
in this case, and construct a list which is then indexed by cond. (Although 
in this case a bytecode compiler might be smart enough to avoid constructing 
the list, it can't do that with my example because the code might depend on 
both those options being evaluated.)


--
Bartc 


--
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-23 Thread Marko Rauhamaa
BartC b...@freeuk.com:

 Ah, but what would

 x = [f, g][cond]()

 produce?

 It will select f or g (which should refer to functions), and call one of
 those depending on cond. That's not a problem.

 The problem is it will still evaluate both f and g,

That's not really the problem. The problem is in readability.

However, the [f, g][cond]() technique is how pure lambda calculus
implements conditional branching so it is interesting in its own right.
IOW, you can do short-circuiting in purely functional programming:

j = j + 1 if j  10 else 3

=

j = (lambda: 3, lambda: j + 1)[j  10]()


Marko
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-23 Thread Ian Kelly
On Thu, Oct 23, 2014 at 7:44 AM, Marko Rauhamaa ma...@pacujo.net wrote:
 However, the [f, g][cond]() technique is how pure lambda calculus
 implements conditional branching so it is interesting in its own right.

I wasn't aware that lambda calculus had lists and indexing built in.

 IOW, you can do short-circuiting in purely functional programming:

 j = j + 1 if j  10 else 3

 =

 j = (lambda: 3, lambda: j + 1)[j  10]()

The implementation given by Wikipedia (and translated into Python by me) is:

 true = lambda x: lambda y: x
 false = lambda x: lambda y: y
 ifthenelse = lambda p: lambda a: lambda b: p(a)(b)
 ifthenelse(true)(1)(2)
1
 ifthenelse(false)(1)(2)
2

For demonstration purposes I used Python ints as the branches rather
than actual lambda calculus constructs, but this shows how selection
can be done using only lambda abstractions and applications.

In any case I don't see how this relates to the [f, g][cond]()
technique of Python, unless you just meant the general approach of
first selecting a function and then applying it. In that sense though,
the ternary operator does the same thing; the application is just done
invisibly by the language in the form of evaluating an expression as
opposed to explicitly applying a function.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-23 Thread Alain Ketterlin
Marko Rauhamaa ma...@pacujo.net writes:

 BartC b...@freeuk.com:

 x = [f, g][cond]()

 It will select f or g (which should refer to functions), and call one of
 those depending on cond. That's not a problem.

 The problem is it will still evaluate both f and g,

 That's not really the problem. The problem is in readability.

Readability is in the eye of the beholder. The evaluation is the central
concern here.

 However, the [f, g][cond]() technique is how pure lambda calculus
 implements conditional branching so it is interesting in its own
 right.

Yes, but lambda calculus constructs have no meaning without an
evaluation strategy (reduction strategy in lambda calculs parlance).

 IOW, you can do short-circuiting in purely functional programming:

 j = j + 1 if j  10 else 3
 =
 j = (lambda: 3, lambda: j + 1)[j  10]()

This is just a way to delay evaluation *of the potential results*, i.e.,
instill a bit of lazyness. One could object that, again, both
expressions in the tuple have been evaluated (building two lambdas),
only one of which is finally called. I guess that's what BartC meant.

-- Alain.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-23 Thread Marko Rauhamaa
Alain Ketterlin al...@dpt-info.u-strasbg.fr:

 j = (lambda: 3, lambda: j + 1)[j  10]()

 This is just a way to delay evaluation *of the potential results*,
 i.e., instill a bit of lazyness.

That's one way to characterize a function, or code in general.

That point of view is apparent in PostScript, where control structures
are expressed lazily with lambdas:

5 eq {
gsave
0.85 1 0.85 setrgbcolor
fill
grestore
} if

The { ... } block is a piece of code pushed onto the stack.


Marko
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-22 Thread Jean-Michel Pichavant
- Original Message -
 From: ast nom...@invalid.com
 To: python-list@python.org
 Sent: Wednesday, 22 October, 2014 10:29:43 AM
 Subject: (test) ? a:b
 
 Hello
 
 Is there in Python something like:
 
 j = (j = 10) ? 3 : j+1;
 
 as in C language ?
 
 thx

j = 3 if j =10 else j+1

Cheers

JM


-- IMPORTANT NOTICE: 

The contents of this email and any attachments are confidential and may also be 
privileged. If you are not the intended recipient, please notify the sender 
immediately and do not disclose the contents to any other person, use it for 
any purpose, or store or copy the information in any medium. Thank you.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-22 Thread buscacio
Em quarta-feira, 22 de outubro de 2014 06h29min55s UTC-2, ast  escreveu:
 Hello
 
 
 
 Is there in Python something like:
 
 
 
 j = (j = 10) ? 3 : j+1;
 
 
 
 as in C language ?
 
 
 
 thx

without not:
j = [j+1, 3][j=10]
with not:
j = [3, j+1][not (j=10)]

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-22 Thread Chris Angelico
On Wed, Oct 22, 2014 at 8:05 PM,  busca...@gmail.com wrote:
 Em quarta-feira, 22 de outubro de 2014 06h29min55s UTC-2, ast  escreveu:
 Hello



 Is there in Python something like:



 j = (j = 10) ? 3 : j+1;



 as in C language ?



 thx

 without not:
 j = [j+1, 3][j=10]
 with not:
 j = [3, j+1][not (j=10)]

There's a distinct semantic difference there, though. Compare these:

/* C */
int x = (y != 0) ? 65536/y : 0;

# Python
x = 65536/y if y else 0

# Python, your way
x = [0, 65536/y][y!=0]

Do you see where the problem is?

Plus, subscripting a literal list is far less readable than the
ternary operator.

Also: Please can you avoid Google Groups, or if you must use it,
please at least clean up the excessive blank lines before you post.
I've left them so you can see what we have to cope with. Thanks!

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-22 Thread Mark Lawrence

On 22/10/2014 10:05, busca...@gmail.com wrote:

Em quarta-feira, 22 de outubro de 2014 06h29min55s UTC-2, ast  escreveu:

Hello



Is there in Python something like:



j = (j = 10) ? 3 : j+1;



as in C language ?



thx


without not:
j = [j+1, 3][j=10]
with not:
j = [3, j+1][not (j=10)]



The death penalty should be reintroduced into the UK for two crimes, 
writing code like the above and using google groups.


--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

--
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-22 Thread ast


busca...@gmail.com a écrit dans le message de 
news:7839376e-fc27-4299-ae63-4ddf17ef9...@googlegroups.com...

Em quarta-feira, 22 de outubro de 2014 06h29min55s UTC-2, ast  escreveu:

Hello



Is there in Python something like:



j = (j = 10) ? 3 : j+1;



as in C language ?



thx


without not:
j = [j+1, 3][j=10]
with not:
j = [3, j+1][not (j=10)]



Oh it's a trick !
thx 


--
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-22 Thread Chris Angelico
On Wed, Oct 22, 2014 at 8:16 PM, Mark Lawrence breamore...@yahoo.co.uk wrote:
 without not:
 j = [j+1, 3][j=10]
 with not:
 j = [3, j+1][not (j=10)]


 The death penalty should be reintroduced into the UK for two crimes, writing
 code like the above and using google groups.

No no no. Code like that doesn't deserve death, just community
service. I've seen much MUCH worse... where multiple conditional
expressions get combined arithmetically, and then the result used
somewhere... I also may have been guilty of same, myself, though I'm
going to plead the internet's equivalent of the Fifth Amendment to the
US Constitution and not incriminate myself by showing the code...

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-22 Thread Ned Batchelder

On 10/22/14 5:05 AM, busca...@gmail.com wrote:

Em quarta-feira, 22 de outubro de 2014 06h29min55s UTC-2, ast  escreveu:

Hello



Is there in Python something like:



j = (j = 10) ? 3 : j+1;



as in C language ?



thx


without not:
j = [j+1, 3][j=10]
with not:
j = [3, j+1][not (j=10)]



Why on earth would you recommend this outdated hack, when there's a true 
conditional operator?


j = 3 if j = 10 else j+1

Of course, many people feel like the conditional operator isn't worth 
the squished-up unreadability, but if someone asks for a conditional 
operator, at least show them one!


--
Ned Batchelder, http://nedbatchelder.com

--
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-22 Thread Mark Lawrence

On 22/10/2014 10:27, Chris Angelico wrote:

On Wed, Oct 22, 2014 at 8:16 PM, Mark Lawrence breamore...@yahoo.co.uk wrote:

without not:
j = [j+1, 3][j=10]
with not:
j = [3, j+1][not (j=10)]



The death penalty should be reintroduced into the UK for two crimes, writing
code like the above and using google groups.


No no no. Code like that doesn't deserve death, just community
service. I've seen much MUCH worse... where multiple conditional
expressions get combined arithmetically, and then the result used
somewhere... I also may have been guilty of same, myself, though I'm
going to plead the internet's equivalent of the Fifth Amendment to the
US Constitution and not incriminate myself by showing the code...

ChrisA



Perhaps you're correct.  Is there anything worse than looking at a 
dreadful piece of code that makes no sense at all and knowing that you'd 
written it six months earlier?


--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

--
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-22 Thread Marko Rauhamaa
Ned Batchelder n...@nedbatchelder.com:

 Why on earth would you recommend this outdated hack, when there's a
 true conditional operator? [...] if someone asks for a conditional
 operator, at least show them one!

No good deed goes unpunished.


Marko
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-22 Thread Mark Lawrence

On 22/10/2014 10:14, ast wrote:


busca...@gmail.com a écrit dans le message de
news:7839376e-fc27-4299-ae63-4ddf17ef9...@googlegroups.com...

Em quarta-feira, 22 de outubro de 2014 06h29min55s UTC-2, ast  escreveu:

Hello



Is there in Python something like:



j = (j = 10) ? 3 : j+1;



as in C language ?



thx


without not:
j = [j+1, 3][j=10]
with not:
j = [3, j+1][not (j=10)]



Oh it's a trick !
thx


IMHO it's just dreadful.  Why people insist on messing around like this 
I really don't know, it just drives me nuts.


Also would you please access this list via 
https://mail.python.org/mailman/listinfo/python-list or read and action 
this https://wiki.python.org/moin/GoogleGroupsPython to prevent us 
seeing double line spacing and single line paragraphs, thanks.


--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

--
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-22 Thread Rustom Mody
On Wednesday, October 22, 2014 5:01:08 PM UTC+5:30, Ned Batchelder wrote:
 On 10/22/14 5:05 AM, buscacio wrote:
  Em quarta-feira, 22 de outubro de 2014 06h29min55s UTC-2, ast  escreveu:
  Hello
  Is there in Python something like:
  j = (j = 10) ? 3 : j+1;
  as in C language ?
  thx
  without not:
  j = [j+1, 3][j=10]
  with not:
  j = [3, j+1][not (j=10)]

 Why on earth would you recommend this outdated hack, when there's a true 
 conditional operator?


To learn a bit about the interchangeability of control and data structures?

[Just playing devil's advocate]

Doesn't change the fact that as a practice it should not be done
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-22 Thread alister
On Wed, 22 Oct 2014 12:41:49 +0100, Mark Lawrence wrote:

 On 22/10/2014 10:27, Chris Angelico wrote:
 On Wed, Oct 22, 2014 at 8:16 PM, Mark Lawrence
 breamore...@yahoo.co.uk wrote:
 without not:
 j = [j+1, 3][j=10]
 with not:
 j = [3, j+1][not (j=10)]


 The death penalty should be reintroduced into the UK for two crimes,
 writing code like the above and using google groups.

 No no no. Code like that doesn't deserve death, just community service.
 I've seen much MUCH worse... where multiple conditional expressions get
 combined arithmetically, and then the result used somewhere... I also
 may have been guilty of same, myself, though I'm going to plead the
 internet's equivalent of the Fifth Amendment to the US Constitution and
 not incriminate myself by showing the code...

 ChrisA


 Perhaps you're correct.  Is there anything worse than looking at a
 dreadful piece of code that makes no sense at all and knowing that you'd
 written it six months earlier?

looking a a dreadful piece of unreadable  unfathomable code  knowing 
you wrote it only Yesterday ;-) 



-- 
Chamberlain's Laws:
(1) The big guys always win.
(2) Everything tastes more or less like chicken.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-22 Thread Chris Angelico
On Thu, Oct 23, 2014 at 2:12 AM, alister
alister.nospam.w...@ntlworld.com wrote:
 Perhaps you're correct.  Is there anything worse than looking at a
 dreadful piece of code that makes no sense at all and knowing that you'd
 written it six months earlier?

 looking a a dreadful piece of unreadable  unfathomable code  knowing
 you wrote it only Yesterday ;-)

Sounds like you have some experience with Perl...

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-22 Thread alister
On Thu, 23 Oct 2014 02:18:42 +1100, Chris Angelico wrote:

 On Thu, Oct 23, 2014 at 2:12 AM, alister
 alister.nospam.w...@ntlworld.com wrote:
 Perhaps you're correct.  Is there anything worse than looking at a
 dreadful piece of code that makes no sense at all and knowing that
 you'd written it six months earlier?

 looking a a dreadful piece of unreadable  unfathomable code  knowing
 you wrote it only Yesterday ;-)
 
 Sounds like you have some experience with Perl...
 
 ChrisA

Never met the girl I deny everything.

Actual no experience in perl  my professional programming experience is 
limited to 8 bit assembler (68XX  8051) 30 years ago. 
c  c++ were too low level for my liking so I started looking at python 
for fun on my Linux box's and was blown away by its smoothness.

-- 
On the other hand, life can be an endless parade of TRANSSEXUAL
QUILTING BEES aboard a cruise ship to DISNEYWORLD if only we let it!!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-22 Thread Dan Stromberg
On Wed, Oct 22, 2014 at 2:05 AM,  busca...@gmail.com wrote:
 Em quarta-feira, 22 de outubro de 2014 06h29min55s UTC-2, ast  escreveu:
 Hello



 Is there in Python something like:



 j = (j = 10) ? 3 : j+1;



 as in C language ?



 thx

 without not:
 j = [j+1, 3][j=10]
 with not:
 j = [3, j+1][not (j=10)]

This is not very readable, and eagerly evaluates the two list values.
A proper ternary operator will not evaluate the unused
candidate-result. This matters a little for performance, but matters
more if one or both of the candidate results have side-effects.

It's better to use j = 3 if j = 10 else j + 1.

What you've suggested here was one of the ternary operator workarounds
before a true ternary operator was introduced in 2.5.

I don't use Python's ternary operator much though - I tend to find
if+else more clear, and it shows up well in a debugger. The ternary
operator tends to lead to long one-liners (especially if nested!),
which are usually best avoided.

I'd even go so far as to say that most uses of a ternary operator
probably should be a small function.  It's slower, but it lends itself
to DRY and abstraction better.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-22 Thread Steven D'Aprano
Ned Batchelder wrote:

 On 10/22/14 5:05 AM, busca...@gmail.com wrote:

 without not:
 j = [j+1, 3][j=10]
 with not:
 j = [3, j+1][not (j=10)]

 
 Why on earth would you recommend this outdated hack, when there's a true
 conditional operator?
 
  j = 3 if j = 10 else j+1

I think that's a bit harsh. Especially since this appears to have been
Buscacio's first post here. Hopefully not his(?) last post!

The old (b, a)[condition] idiom is not outdated for anyone supporting Python
2.4, and I wouldn't call it a hack. Indexing into a sequence with a bool is
basic to Python's semantics: True and False are ints equal to 1 and 0
respectively. It's also a technique easily extensible to more than two
values:

'01TX'[n % 4]

is in my opinion more readable than:

i = n % 4
'0' if i == 0 else '1' if i == 1 else 'T' if i == 3 else 'X'


 Of course, many people feel like the conditional operator isn't worth
 the squished-up unreadability, but if someone asks for a conditional
 operator, at least show them one!

The advantage of the `x if cond else y` operator is that it is a
short-cutting operator, it doesn't evaluate either x or y unless needed.
But for many cases that's not important, and in those cases I won't say I
prefer the old (y, x)[cond] idiom, but neither do I dislike it.


-- 
Steven

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-22 Thread Chris Angelico
On Thu, Oct 23, 2014 at 3:28 AM, Steven D'Aprano
steve+comp.lang.pyt...@pearwood.info wrote:
 It's also a technique easily extensible to more than two
 values:

 '01TX'[n % 4]

 is in my opinion more readable than:

 i = n % 4
 '0' if i == 0 else '1' if i == 1 else 'T' if i == 3 else 'X'

That's true when it's fundamentally arithmetic. But part of that
readability difference is the redundancy in the second one. What if it
weren't so redundant?

'Negative' if x  0 else 'Low' if x  10 else 'Mid' if x  20 else 'High'

You can't easily turn that into a dict lookup, nor indexing. It's
either a chained if/elif tree or nested if/else expressions, which
come to the same thing. So I'd say all the techniques have their
advantages and disadvantages. The most important thing to note is
where they differ in semantics, like the short-circuiting of if/else.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-22 Thread Michael Torrie
On 10/22/2014 05:45 AM, Mark Lawrence wrote:
 without not:
 j = [j+1, 3][j=10]
 with not:
 j = [3, j+1][not (j=10)]


 Oh it's a trick !
 thx
 
 IMHO it's just dreadful.  Why people insist on messing around like this 
 I really don't know, it just drives me nuts.

This actually was the standard idiom used by many python programs before
Python 2.5.  But I agree.  Don't do this anymore! Python has a ternary
if expression. Also the ternary if expression does, I believe
short-circuit logic, so the non-chosen path is not calculated.  This
hack does not. Could lead to interesting bugs depending on your assumptions.

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-22 Thread alister
On Thu, 23 Oct 2014 03:28:48 +1100, Steven D'Aprano wrote:

 Why on earth would you recommend this outdated hack, when there's a
 true conditional operator?
 
  j = 3 if j = 10 else j+1
 
 I think that's a bit harsh. Especially since this appears to have been
 Buscacio's first post here. Hopefully not his(?) last post!
 
 The old (b, a)[condition] idiom is not outdated for anyone supporting
 Python 2.4, and I wouldn't call it a hack. Indexing into a sequence with
 a bool is basic to Python's semantics: True and False are ints equal to
 1 and 0 respectively. It's also a technique easily extensible to more
 than two values:
 
 '01TX'[n % 4]
 
 is in my opinion more readable than:
 
 i = n % 4 '0' if i == 0 else '1' if i == 1 else 'T' if i == 3 else
 'X'

chained ternary operations are evil no mater what style or language they 
are written in as they rapidly become confusing  unreadable

Readability counts

in my opinion they are better written as nested if statements 

-- 
Ambiguity:
Telling the truth when you don't mean to.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-22 Thread BartC



Rustom Mody rustompm...@gmail.com wrote in message 
news:7d2ea3c1-504e-4f5c-8338-501b1483d...@googlegroups.com...

On Wednesday, October 22, 2014 5:01:08 PM UTC+5:30, Ned Batchelder wrote:

On 10/22/14 5:05 AM, buscacio wrote:
 Em quarta-feira, 22 de outubro de 2014 06h29min55s UTC-2, ast 
 escreveu:

 Hello
 Is there in Python something like:
 j = (j = 10) ? 3 : j+1;
 as in C language ?
 thx
 without not:
 j = [j+1, 3][j=10]
 with not:
 j = [3, j+1][not (j=10)]



Why on earth would you recommend this outdated hack, when there's a true
conditional operator?



To learn a bit about the interchangeability of control and data 
structures?


[Just playing devil's advocate]


But it doesn't do the same thing.

Comparing:

x = cond ? f() : g();   # C version

with

x = [f(), g()] [cond]

the latter evaluates both f() and g() instead of just one. Apart from being 
inefficient, it can have unintended side-effects.


--
Bartc



--
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-22 Thread Matthew Ruffalo
On 10/22/2014 12:40 PM, Chris Angelico wrote:
 That's true when it's fundamentally arithmetic. But part of that
 readability difference is the redundancy in the second one. What if it
 weren't so redundant?

 'Negative' if x  0 else 'Low' if x  10 else 'Mid' if x  20 else 'High'

 You can't easily turn that into a dict lookup, nor indexing. It's
 either a chained if/elif tree or nested if/else expressions, which
 come to the same thing.
No, you can't turn that into a dict lookup, but this is one of the
canonical use cases for the bisect module:

 from bisect import bisect
 breakpoints = [0, 10, 20]
 labels = ['Negative', 'Low', 'Mid', 'High']
 values = [-5, 5, 15, 25]
 [labels[bisect(breakpoints, value)] for value in values]
['Negative', 'Low', 'Mid', 'High']

It's also worth noting that using bisect is O(log(n)) instead of O(n),
but if you're going to hit a point where the asymptotic behavior matters
I'm sure you will have long since abandoned a manually-written if/elif
chain.

MMR...

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-22 Thread Chris Angelico
On Thu, Oct 23, 2014 at 5:27 AM, Matthew Ruffalo mm...@case.edu wrote:
 On 10/22/2014 12:40 PM, Chris Angelico wrote:
 That's true when it's fundamentally arithmetic. But part of that
 readability difference is the redundancy in the second one. What if it
 weren't so redundant?

 'Negative' if x  0 else 'Low' if x  10 else 'Mid' if x  20 else 'High'

 You can't easily turn that into a dict lookup, nor indexing. It's
 either a chained if/elif tree or nested if/else expressions, which
 come to the same thing.
 No, you can't turn that into a dict lookup, but this is one of the
 canonical use cases for the bisect module:

 from bisect import bisect
 breakpoints = [0, 10, 20]
 labels = ['Negative', 'Low', 'Mid', 'High']
 values = [-5, 5, 15, 25]
 [labels[bisect(breakpoints, value)] for value in values]
 ['Negative', 'Low', 'Mid', 'High']

 It's also worth noting that using bisect is O(log(n)) instead of O(n),
 but if you're going to hit a point where the asymptotic behavior matters
 I'm sure you will have long since abandoned a manually-written if/elif
 chain.

Indeed. If the performance is making any difference, something's gone
wrong. I'm seeing that as not significantly clearer than the chained
if/else statement or expression: you need a list of breakpoints and a
list of results, which need to be kept in sync. But there's probably
no ideal solution to this.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-22 Thread Ned Batchelder

On 10/22/14 12:28 PM, Steven D'Aprano wrote:

Ned Batchelder wrote:


On 10/22/14 5:05 AM, busca...@gmail.com wrote:



without not:
j = [j+1, 3][j=10]
with not:
j = [3, j+1][not (j=10)]



Why on earth would you recommend this outdated hack, when there's a true
conditional operator?

  j = 3 if j = 10 else j+1


I think that's a bit harsh. Especially since this appears to have been
Buscacio's first post here. Hopefully not his(?) last post!


You are right, it sounds a bit harsh. Sorry.

--
Ned Batchelder, http://nedbatchelder.com

--
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-22 Thread Steven D'Aprano
Michael Torrie wrote:

 On 10/22/2014 05:45 AM, Mark Lawrence wrote:
 without not:
 j = [j+1, 3][j=10]
 with not:
 j = [3, j+1][not (j=10)]


 Oh it's a trick !
 thx
 
 IMHO it's just dreadful.  Why people insist on messing around like this
 I really don't know, it just drives me nuts.
 
 This actually was the standard idiom used by many python programs before
 Python 2.5.  But I agree.  Don't do this anymore! Python has a ternary
 if expression. Also the ternary if expression does, I believe
 short-circuit logic, so the non-chosen path is not calculated.  This
 hack does not. Could lead to interesting bugs depending on your
 assumptions.

Working code doesn't suddenly become non-working code just because Python
adds a second way to do something. The standard idiom

(value_if_false, value_if_true)[condition]

worked from (at least) Python 1.5 to Python 2.4, and it continues to work
today. There's nothing wrong with it: it does what it does, nothing more,
nothing less, and the only hashish part of this is that bools *are* ints,
with True == 1 and False == 0. That was heavily debated back in 2.3 or
thereabouts when bools were first introduced, and the decision made then
wasn't reverted in Python 3, so you can take it as By Design and not a
fluke of history. I think it is fair to say that Guido likes it that bools
are ints.

The older idiom isn't *exactly* the same as the ternary if operator, since
that short-circuits, but for many purposes short-circuiting is not
important or needed. If you don't need short-circuiting, or you dislike the
order of `value_if_true if condition else value_if_false`, or you need to
support Python 2.4 or older, or *simply because you like it*, there is
nothing wrong with using the older `sequence[flag]` idiom.

(It amuses me that not that many years ago the general attitude here was
that ternary if was an abomination that no right-thinking person should
ever use because the order of terms isn't identical to C, and now the
attitude seems to be that anyone *not* using ternary if is a heretic who
deserves to be set on fire :-)



-- 
Steven

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-22 Thread Gregory Ewing

Chris Angelico wrote:

I've seen much MUCH worse... where multiple conditional
expressions get combined arithmetically, and then the result used
somewhere...


In the days of old-school BASIC it was common to
exploit the fact that boolean expressions evaluated
to 0 or 1 (or -1, depending on your dialect :) to
achieve conditional expressions or other tricks.

Probably forgiveable, given that there were no real
conditional expressions, and every byte of your 48K
or less of RAM was precious...

--
Greg
--
https://mail.python.org/mailman/listinfo/python-list


Re: (test) ? a:b

2014-10-22 Thread Vito De Tullio
Dennis Lee Bieber wrote:

 x = [f(), g()] [cond]

the latter evaluates both f() and g() instead of just one. Apart from
being inefficient, it can have unintended side-effects.
 
 Ah, but what would
 
 x = [f, g][cond]()
 
 produce?


headache

-- 
By ZeD

-- 
https://mail.python.org/mailman/listinfo/python-list