Why isn't there a conditional operator (a ? b : c) in Python? 2.0 now
has augmented assignments, and the FAQ even acknowledges that the
conditional operator is sometimes quite convenient and gives some (very
awkward) Python alternatives.
I've been reading comp.lang.python for a while (since just before 2.0
shipped) and I can't really remember much discussion about it. Is it a
perennial request and I'm just missing it?
--
Erik Max Francis / m...@alcyone.com / http://www.alcyone.com/max/
__ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE
/ \ I sidestep the either
\__/ or choices of logic and choose both. | Ken Feit
Product's Quake III Arena Tips / http://www.bosskey.net/
Tips and tricks from the absolute beginner to the Arena Master.
>>> 1 and 2 or 3
2
>>> 0 and 2 or 3
3
HTH,
--
Emile van Sebille
em...@fenx.com
---------
"Erik Max Francis" <m...@alcyone.com> wrote in message
news:3AC68CB8...@alcyone.com...
:Why isn't there a conditional operator (a ? b : c) in Python?
This can be implemented in Python by using the 'and' and 'or' operators. I
wish I could remember where I saw the explanation, but I can't remember
whether it was in Chun's _Core Python Programming_ or the "Dive Into Python"
website. In any case, I can't find it right now.
From Kernighan and Ritchie, page 51:
"""
The <i>conditional experssion<i>, written with the ternary operator "?:",
provides an alternate way to write this and similar constructions. In the
expression
expr1 ? expr2 : expr3
the expression expr1 is evaluate first. If it is non-zero (true), then the
expression expr2 is evaluated, and that is the value of the conditional
expression. Otherwise, expr3 is evaluated, and that is the value. Only one of
expr2 and expr3 is evaluated. Thus to set z to the maximum of a and b,
z = ( a > b ) ? a : b; /* z = max(a,b) */
"""
I'm sure I saw this on the "Dive into Python" site...? (Ok, I finally found
the reference, here:
http://diveintopython.org/apihelper_andor.html )
How can we do this in Python using 'and' and 'or'...
in Python:
a and b returns the value of b if a is true, else returns the value of a
a or b returns the value of a if a is true, else returns the value of b
So, to return the max of a or b I could do
return ( a > b ) and a or b
Here is an interpreter session:
>>> a = 5
>>> b = 3
>>> (a > b) and a or b
5
>>> a = 2
>>> b = 12
>>> (a > b) and a or b
12
>>>
--
Sheila King
http://www.thinkspot.net/sheila/
http://www.k12groups.org/
: 2.0 now
>Why isn't there a conditional operator (a ? b : c) in Python?
Because trying to come with a semantically identical construct
in Python provides many hours of fun and a never-ending Usenet
thread. ;)
>I've been reading comp.lang.python for a while (since just before 2.0
>shipped) and I can't really remember much discussion about it. Is it a
>perennial request and I'm just missing it?
It comes up every month or two.
--
Grant Edwards grante Yow! Here I am at the flea
at market but nobody is buying
visi.com my urine sample bottles...
Eric, there's no feature from *any* language that isn't regularly suggested
for Python. This one is regularly requested too, but is down in the noise.
Its most persistent proponent today is Eric Raymond, and you might want to
nag him to finish his long-threatened PEP on the topic.
In the meantime, try if/then/else <wink>.
hey-it-works-for-me-ly y'rs - tim
I have never once seen somebody suggest that we have either FORTRAN-style
computed gotos or counted hollerith constants :-)
This is not equivalent in the general case.
0 ? 0 : 1 --> 0
0 and 0 or 1 --> 1
--
Rainer Deyke (ro...@rainerdeyke.com)
Shareware computer games - http://rainerdeyke.com
"In ihren Reihen zu stehen heisst unter Feinden zu kaempfen" - Abigor
> Yes, it comes up. Generally, except for short-circuiting, the
> solutions
> follow:
>
> >>> 1 and 2 or 3
> 2
> >>> 0 and 2 or 3
> 3
Yeah, but the short-circuiting exceptions are what make that construct
not worth using, since if used identically as a replacement for a
conditional expression, it won't work when a is 0 (or any other
expression that evaluates to false).
There's a failsafe solution, which is just to use an if: ... else: ...
statement. I was just wondering why it hasn't crept into Python at some
point, especially since augmented assignments already have, and seem at
the same level of "convenience" (arguably less in fact, since an
augmented assignment is still a statement, not an expression).
--
Erik Max Francis / m...@alcyone.com / http://www.alcyone.com/max/
__ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE
/ \ If I had known, I would have become a watchmaker.
\__/ Albert Einstein
blackgirl international / http://www.blackgirl.org/
The Internet resource for black women.
Easily, if unreadably, solved: (condition and (a,) or (b,))[0]
--
Barnabas T. Rumjuggler
You do not use a macintosh instead you use a tandy
Kompressor break your glowstick Kompressor eat your candy
> This is not equivalent in the general case.
>
> 0 ? 0 : 1 --> 0
> 0 and 0 or 1 --> 1
Indeed, which negates most of the benefit of trying to use such a
substituted expression in Python -- the conditional operator is useful
because it is straightforward and clear. The Python FAQ, for instance,
suggests x ? a : b can be reliably substituted with
(x and [a] or [b])[0]
which definitely works ([a] and [b] are singleton lists and always
evaluate true), but it makes the meaning unclear enough to defeat the
purpose of wanting to use a conditional operator in the first place.
For cases where I know that the testing value will be a "boolean" (0 or
1 and nothing else), I generally do something like
[a, b][x]
which ain't great but is better than the former.
Still, one can hope.
On a vaguely related subject, why is there no Boolean type in Python?
Seems like it would clean things up a great deal -- my understanding is
that there is even an internal Python Boolean type, but it is hidden in
the interpreter. How come?
--
Erik Max Francis / m...@alcyone.com / http://www.alcyone.com/max/
__ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE
> Easily, if unreadably, solved: (condition and (a,) or (b,))[0]
Sure, but unfortunately the unreadable part defeats the whole purpose
for wanting a conditional operator in the first place :-).
> Eric, there's no feature from *any* language that isn't regularly suggested
> for Python.
I haven't seen many suggestions that we adopt APL's syntax and
character set.
RATS...and April 1 would have been the perfect day for such a request.
Ah, well...next year.
--John
LOL! I "invented" that "idiom" for Python in the early 90's, in a silly
thread where Steven Majewski and I tortured each other with the worst
constructs we could dream up. If you ever see production code that actually
*uses* it, I encourage you to kill the author.
> ...
> On a vaguely related subject, why is there no Boolean type in Python?
Because Guido didn't feel one was needed. Still doesn't, last I heard.
Barry Warsaw is a big fan of adding one, though, and since he got "print >>
file" in, there's no known lower limit on the uselessness of the ideas he can
sell <wink>.
next-up:-how-come-there-isn't-a-case-stmt?-ly y'rs - endless tim
> The Python FAQ, for instance, suggests x ? a : b can be reliably
> substituted with
>
> (x and [a] or [b])[0]
It computes both a and b. A correct solution is
(0 and (lambda: a) or (lambda: b))()
Yes, it is ugly.
--
__("< Marcin Kowalczyk * qrc...@knm.org.pl http://qrczak.ids.net.pl/
\__/
^^ SYGNATURA ZASTĘPCZA
QRCZAK
Umm...there's a good argument for using it in "Dive into Python"
<http://diveintopython.org/apihelper_andor.html>, that you can use
conditionals in a lambda where an <if...> is not allowed.
Made sense to me.
But then, I don't know much.
to me, that sounds like a good argument not to use lambdas
in that situation...
here's the eff-bot's favourite lambda refactoring rule:
1) write a lambda function
2) write a comment explaining what the heck that lambda does
3) study the comment for a while, and think of a name that captures
the essence of the comment
4) convert the lambda to a def statement, using that name
5) remove the comment
Cheers /F
> Sat, 31 Mar 2001 21:22:54 -0800, Erik Max Francis <m...@alcyone.com> pisze:
>
> > The Python FAQ, for instance, suggests x ? a : b can be reliably
> > substituted with
> >
> > (x and [a] or [b])[0]
>
> It computes both a and b.
No it doesn't:
/>> def f():
|.. print 1
|.. return 1
\__
/>> def g():
|.. print 2
|.. return 2
\__
->> (0 and [f()] or [g()])[0]
2
2
->> (1 and [f()] or [g()])[0]
1
1
> A correct solution is
> (0 and (lambda: a) or (lambda: b))()
This also works.
> Yes, it is ugly.
This is also true.
Cheers,
M.
--
. <- the point your article -> .
|------------------------- a long way ------------------------|
-- Cristophe Rhodes, ucam.chat
> > > (x and [a] or [b])[0]
> >
> > It computes both a and b.
>
> No it doesn't:
Oops, of course, stupid me.
Hey! That's pretty good. Keep it in a cut'n'paste buffer.
--
--- Aahz <*> (Copyright 2001 by aa...@pobox.com)
Androgynous poly kinky vanilla queer het Pythonista http://www.rahul.net/aahz/
Hugs and backrubs -- I break Rule 6
"I put people on my humor list as a form of revenge, you realize." --SJM
[Marcin 'Qrczak' Kowalczyk]
> It computes both a and b.
Nope, it doesn't. If x is true it evaluates only a; if x false, only b.
> A correct solution is
> (0 and (lambda: a) or (lambda: b))()
Only if x is always false <wink>, repair the typo, and you're still left with
"the usual" namespace visibility surprises.
> Yes, it is ugly.
They both are. Use if/then/else, for Parrot's sake.
>So, to return the max of a or b I could do
>
>return ( a > b ) and a or b
>
>Here is an interpreter session:
>
>>>> a = 5
>>>> b = 3
>>>> (a > b) and a or b
>5
>>>> a = 2
>>>> b = 12
>>>> (a > b) and a or b
>12
>>>>
>
Please don't do this, as it doesn't do what you think.
>>> a = 0
>>> b = -5
>>> (a > b) and a or b
-5
and consider that one of the common uses for a max function is to set a
lower bound of 0 on a calculation.
Why 5)?
John
Thomas
:
:Please don't do this, as it doesn't do what you think.
:
:>>> a = 0
:>>> b = -5
:>>> (a > b) and a or b
:-5
:
:and consider that one of the common uses for a max function is to set a
:lower bound of 0 on a calculation.
The reference I sited in the post you are replying to:
http://diveintopython.org/apihelper_andor.html
goes over that difficulty and how to get around it.
Still, I personally wouldn't use this method. if-else seems fine to me?
>...
>On a vaguely related subject, why is there no Boolean type in Python?
>Seems like it would clean things up a great deal -- my understanding is
>that there is even an internal Python Boolean type, but it is hidden in
>the interpreter. How come?
I suspect the basic reason is because C doesn't have one. But that's
just a guess.
I personally dislike the concept that "every variable has a boolean
value", and the associated fact that utterly different values have the
same logical value. But hey, a large numer of languages work this way
and it doesn't seem to cause too much trouble. (Though I think Python
would benefit from a built in function that tests for logical equality
-- if I'm missing one, please enlighten me; the best I've come up with
so far is: not a == not b, which is not exactly obvious.)
But even if the Python development team suddenly became convinced that a
separate boolean type was the way to go, it'd be quite a challenge to
implement such a thing without breaking a vast amount of existing code.
-- Russell
I figured it was because a "boolean" is more theoretical than anything
else, or at least never the whole story. Tri-state would be much more
useful -- true, false, don't know -- but what do you do in the case of
"don't know"... use a default truth value, the tv of another object
(determined at the time the boolean is created, or when the tv is
being looked at?), or provide a hook and let the coder handle it
(ending up with different classes of booleans)?
> I personally dislike the concept that "every variable has a boolean
> value", and the associated fact that utterly different values have the
> same logical value. But hey, a large numer of languages work this way
> and it doesn't seem to cause too much trouble. (Though I think Python
> would benefit from a built in function that tests for logical equality
> -- if I'm missing one, please enlighten me; the best I've come up with
> so far is: not a == not b, which is not exactly obvious.)
If you use 0 == false and 1 == true, the bit-wise exclusive-or is a
negative logic version of what you want:
A B xor
0 0 0
0 1 1
1 0 1
1 1 0
I coded up a tri-state "Boolean" class awhile back that supports
all the logical operations, truth-value testing, and "mixed mode"
boolean arithmetic (* == and, + == or)... I could clean it up and make
it public if anyone is interested (although a consensus on the
questions I posed above would be helpful, since that is where I got
wishy-washy before I moved onto something else).
> But even if the Python development team suddenly became convinced that a
> separate boolean type was the way to go, it'd be quite a challenge to
> implement such a thing without breaking a vast amount of existing code.
Why would adding something to the language break old code...
just don't change the old behaviour.
- Bruce
I figured it was because a "boolean" is more theoretical than anything
else, or at least never the whole story. Tri-state would be much more
useful -- true, false, don't know -- but what do you do in the case of
"don't know"... use a default truth value, the tv of another object
(determined at the time the boolean is created, or when the tv is
being looked at?), or provide a hook and let the coder handle it
(ending up with different classes of booleans)?
> I personally dislike the concept that "every variable has a boolean
> value", and the associated fact that utterly different values have the
> same logical value. But hey, a large numer of languages work this way
> and it doesn't seem to cause too much trouble. (Though I think Python
> would benefit from a built in function that tests for logical equality
> -- if I'm missing one, please enlighten me; the best I've come up with
> so far is: not a == not b, which is not exactly obvious.)
If you use 0 == false and 1 == true, the bit-wise exclusive-or is a
negative logic version of what you want:
A B xor
0 0 0
0 1 1
1 0 1
1 1 0
I coded up a tri-state "Boolean" class awhile back that supports
all the logical operations, truth-value testing, and "mixed mode"
boolean arithmetic (* == and, + == or)... I could clean it up and make
it public if anyone is interested (although a consensus on the
questions I posed above would be helpful, since that is where I got
wishy-washy before I moved onto something else).
> But even if the Python development team suddenly became convinced that a
> separate boolean type was the way to go, it'd be quite a challenge to
> implement such a thing without breaking a vast amount of existing code.
Why would adding something to the language break old code...
>> But even if the Python development team suddenly became convinced that a
>> separate boolean type was the way to go, it'd be quite a challenge to
>> implement such a thing without breaking a vast amount of existing code.
>
>Why would adding something to the language break old code...
>just don't change the old behaviour.
Simply adding "true" and "false" constants or keywords or what-have-you
would certainly clarify some code and would also certainly NOT break
anything except code that already used these as names. I suspect most
folks are not foolish enough to code with "true" or "false" (unless they
are used to mean the obvious, in which case only the code that
initializes them would break).
However, the broader issue is of a separate boolean type used for all
logical operations. I personally think it's quite messy and confusing
that any value has an associated logical value (e.g. 0 is false, any
other integer is true, "" is false, any other string is true, etc.). But
as I said in my previous posting, it's a widely used construct that
doesn't seem to screw up languages too badly. And there's no way to
change this in Python without breaking tons of code.
Regarding your boolean class, could you explain the value to adding
"don't know" to it? I can imagine it has its uses, but it sounds like a
different problem domain than standard conditional logic such as
if/then/else. If you're aiming for fuzz logic then presumably you'd want
more choices than simply true, false and don't know.
-- russell
I'd like to see a 'boolean' type added, with 2 (constant) instances,
'true' and 'false' in __builtins__. Putting them in __builtins__
wouldn't break even the code that initialized them (for example, try
None = "foo" ).
If I get around to it I might write a PEP. I would design 'true' and
'false' to compare against objects in the current fashion. For
example,
if "" == false :
print '"" is false'
would execute the print statement. The real usefulness is as an
argument or return value to/from a function. IMO the following is
clearer than the current alternatives in self-documenting the purpose
of it :
setVisible( true )
or
def is_condition( ) :
return true
In these cases it is clear that the return value is supposed to
indicate boolean usage, rather than possibly appearing to be
arithmetic.
| Regarding your boolean class, could you explain the value to adding
| "don't know" to it? I can imagine it has its uses, but it sounds like a
If you want to have a (cache) flag somewhere, you would first set it
to "don't know", aka "not initialized yet". Then in the first
usage you could do the computation and set the flag to true or false.
Afterwards you simply need to check the flag and not perform the
computation again.
-D
Are you perchance assuming that everybody's variable names are
in English...?
> Regarding your boolean class, could you explain the value to adding
> "don't know" to it? I can imagine it has its uses, but it sounds like a
> different problem domain than standard conditional logic such as
> if/then/else. If you're aiming for fuzz logic then presumably you'd want
Standard SQL adds a "don't know/not applicable" value (NULL) to
_every_ datatype, including booleans. It's really a must to handle
masses of data collected in the real world, as some 'holes' due to
imperfect data-collection remains most often, and using an otherwise
permissible data-value to map "don't know" is pernicious (most
particularly for data-types wit few permissible values -- boolean
is a sort of worst-case here!-).
Alex
ok
> Regarding your boolean class, could you explain the value to adding
> "don't know" to it? I can imagine it has its uses, but it sounds like a
> different problem domain than standard conditional logic such as
> if/then/else. If you're aiming for fuzz logic then presumably you'd want
> more choices than simply true, false and don't know.
It was really just a `learning Python' exercise, no specific problem,
but I did have this in mind...
What do you do when you want boolean data from a remote site, but the
link is down. You could give up and wait for the link to come back,
use a hardcoded default, or defer to something else which returns a
value you can use. All I did was include the definition of what to do
in the boolean class so the three cases could be handled as such:
# this will raise an exception when the tv of "a" is looked at if
# get_state returned None
a = Boolean(val=get_state(), assume=None)
# get_state still returns None, but the tv of "a" will be "false"
a = Boolean(val=get_state(), assume=0)
# the tv of a will be whatever what_to_assume returns
a = Boolean(val=get_state(), assume=what_to_assume())
The complete tt looks like this (tv() is a method of Boolean
which lets you turn off the potential exception raising if the tv is
indeterminate):
assume value | tv(0)* tv(1)
------ ------ | ------- -----
None None | TVError None
None 0 | 0 0
None 1 | 1 1
0 None | 0 0
0 0 | 0 0
0 1 | 1 1
1 None | 1 1
1 0 | 0 0
1 1 | 1 1
* operations (e.g., &, |, not, etc.) act like tv(0)
How useful these semantics are in the real world is something I could
only guess at, but one could sure come up with some hard to figure but
succinct code if the obj and assume parameters are themselves
tri-state "booleans" (and you happen to need that kind of complicated
logical functionality in enough places to warrant adding yet another
class to your code).
The only fuzzy logic I've seen is the implementation in logic.py
at the Vaults of Parnassus, it looks more like a probability thing
than logic <shrug>.
- Bruce
ok
> Regarding your boolean class, could you explain the value to adding
> "don't know" to it? I can imagine it has its uses, but it sounds like a
> different problem domain than standard conditional logic such as
> if/then/else. If you're aiming for fuzz logic then presumably you'd want
> more choices than simply true, false and don't know.
It was really just a `learning Python' exercise, no specific problem,
but I did have this in mind...
What do you do when you want boolean data from a remote site, but the
link is down. You could give up and wait for the link to come back,
use a hardcoded default, or defer to something else which returns a
value you can use. All I did was include the definition of what to do
in the boolean class so the three cases could be handled as such:
# this will raise an exception when the tv of "a" is looked at if
# get_state returned None
a = Boolean(val=get_state(), assume=None)
# get_state still returns None, but the tv of "a" will be "false"
a = Boolean(val=get_state(), assume=0)
# the tv of a will be whatever what_to_assume returns
a = Boolean(val=get_state(), assume=what_to_assume())
The complete tt looks like this (tv() is a method of Boolean
which lets you turn off the potential exception raising if the tv is
indeterminate):
assume value | tv(0)* tv(1)
------ ------ | ------- -----
None None | TVError None
None 0 | 0 0
None 1 | 1 1
0 None | 0 0
0 0 | 0 0
0 1 | 1 1
[stuff about (cond and trueVal or falseVal) ]
> > This is not equivalent in the general case.
> > > 0 ? 0 : 1 --> 0
> > 0 and 0 or 1 --> 1
>
> Indeed, which negates most of the benefit of trying to use such a
> substituted expression in Python -- the conditional operator is useful
> because it is straightforward and clear. The Python FAQ, for instance,
> suggests x ? a : b can be reliably substituted with
>
> (x and [a] or [b])[0]
>
> which definitely works ([a] and [b] are singleton lists and always
> evaluate true), but it makes the meaning unclear enough to defeat the
> purpose of wanting to use a conditional operator in the first place.
>
Hey... it's a good question. Tools like list comprehensions make it
quite easy to use a functional style with python code for a lot of
things, and it's very useful tool. But that's where the need for a
conditional statement is strongest. Of course it's not necessary...
I use
def cond(test, trueval, falseval):
if test:
return trueval
else:
return falseval
a bit. But it'd be more convenient if there were a true,
short-circuiting version available. Are there any good reasons
NOT do do so? (The uglyness of "?:" is not a valid reason... I
KNOW the Python community can find a cleaner syntax.) One obvious
reason is that it adds yet one more control structure to the
language (which we want to keep small), but are there any other
reasons you can think of?
-- Michael Chermside
FORTRAN-style spaces in identifiers on the other hand ..
--
--
Amit J Patel, Computer Science Department, Stanford University
http://www-cs-students.stanford.edu/~amitp/
You don't even need 'and' / 'or' anymore:
(lambda t:([a for i in (1,) if t]+[b for i in (1,) if not t])[0])(x)
<duck>
- Amit
...would no doubt be considered 'cool' by the same kind of people who
like the idea of naming standard folders in such ways as "Program Files",
"My Documents", "Windows Update Setup Files", and other space-containing
strings (thus requiring abundant preventive quoting in program startup
strings &c -- yecch). Avoiding clever parser look-ahead to distinguish
for a in b:
from
forainb = 23
seems a much better idea to me (and I _am_ an old Fortran hand!-).
I suspect spaces (or underscores?) within _numeric literals_ might
prove more popular -- I'd LOVE to be able to write, e.g.:
a = 1 000 000 000
to make the number "one billion" more legible -- but maybe it's not
as good an idea as it seems at first glance: if the number of digits
between separating spaces was not checked, it might be misleading;
if it WAS checked, then I'm not sure that "three by three" is OK in
all locales (but maybe non-US locales need not be supported here,
just as they aren't, for example, for decimal-point). [Commas as
digit-separators in literals are not acceptable because of backwards
compatibility -- "a=1,000" already has meaning, binding a to a tuple
of 2 elements, of course!].
Alex
I agree about commans, but I don't like using spaces; Ada's solution
of permitting underscores '_' inside numeric literals is a nice
compromise between the limitations of ASCII and the limitations of
human readers.
So the above might be written
a = 1_000_000_000
which is fairly readable and culture non-specific. (Though using
commas as decimal-points is even more brain-damaged than using
periods, which just shocks me -- what's that about fine European
design again? ;)
Neel
It seems he does... But if you *don't* use English variable names,
what is the chance that you'd use the worde "true" and "false"?
(OK, I'm sure they exist in other languages having other meanings,
but no we're not really talking major amounts of code... Or?)
[...]
>
> Alex
--
Magnus Lie Hetland http://www.hetland.org
"Reality is that which, when you stop believing in
it, doesn't go away." -- Philip K. Dick
Actually, I found the best mechanism for my needs, when I did something like
this, was to have an object with a five-state value (definitely, probably,
maybe, probably not, and definitely not), a textual message, and a level
above which this would be considered "true" if all you wanted was a boolean.
So if, for example, you were checking an email address, you could do
something like
definitely - email got delivered
probably - final machine was down, but email got queued on an MX host
maybe - email got queued locally, address is syntactically valid
probably not - heuristics fixed the address and it queued OK
("1234,567" -> 1234...@compuserve.com)
definitely not - Couldn't figure out what the email address was.
Then, for this, you'd likely set the "ok" level at "maybe", meaning "maybe
or better should be treated as success", but you could still check the
details, with the text string available for logging/debugging.
Just a class I found myself using all *over* the place when doing
failure-prone internet stuff.
--
Darren New / Senior MTS & Free Radical / Invisible Worlds Inc.
San Diego, CA, USA (PST). Cryptokeys on demand.
schedule.c:7: warning: assignment makes calendar_week
from programmer_week without a cast.
On Wed, 4 Apr 2001, Alex Martelli wrote:
>
> I suspect spaces (or underscores?) within _numeric literals_ might
> prove more popular -- I'd LOVE to be able to write, e.g.:
> a = 1 000 000 000
> to make the number "one billion" more legible -- but maybe it's not
> as good an idea as it seems at first glance: if the number of digits
> between separating spaces was not checked, it might be misleading;
> if it WAS checked, then I'm not sure that "three by three" is OK in
> all locales (but maybe non-US locales need not be supported here,
> just as they aren't, for example, for decimal-point). [Commas as
> digit-separators in literals are not acceptable because of backwards
> compatibility -- "a=1,000" already has meaning, binding a to a tuple
> of 2 elements, of course!].
Obviously a performance hit, but if you want readability:
>>> def Number( *args ):
... t = 0
... for x in args:
... t = t * 1000L
... assert 0 <= x < 1000, 'Out of range'
... t = t + x
... return t
...
>>> Number( 1,000,000 )
1000000
>>> Number( 1,234,567)
1234567
>>> Number( 1,200,300,400,500 )
1200300400500L
>>> Number( 1,200,300,400,500.25 )
1200300400500.25
Of course, you can also have confusing things like:
>>> Number( 1,2,3 )
1002003
-- Steve
>>>> def Number( *args ):
> ... t = 0
> ... for x in args:
> ... t = t * 1000L
> ... assert 0 <= x < 1000, 'Out of range'
> ... t = t + x
> ... return t
> ...
>>>> Number( 1,000,000 )
> 1000000
>>>> Number( 1,234,567)
> 1234567
>>>> Number( 1,200,300,400,500 )
> 1200300400500L
>>>> Number( 1,200,300,400,500.25 )
> 1200300400500.25
> Of course, you can also have confusing things like:
>>>> Number( 1,2,3 )
> 1002003
Be careful with this--octal notation (numbers beginning with 0) will
break it.
That's not confusing. This is <wink>:
>>> Number(1,064)
1052L
>>>
hard-to-believe-that-semantically-significant-leading-zeroes-
ever-seemed-like-"a-good-idea"-to-anyone-ly y'rs - tim
On Wed, 4 Apr 2001, Tim Peters wrote:
>
> That's not confusing. This is <wink>:
>
> >>> Number(1,064)
> 1052L
> >>>
>
> hard-to-believe-that-semantically-significant-leading-zeroes-
> ever-seemed-like-"a-good-idea"-to-anyone-ly y'rs - tim
>
GROAN!
Well -- it worked for all my test cases!
( Doesn't that sound familiar! )
I'm sure glad I was just giving free advice and not trying to
do something with it myself! ;-)
-- Steve.
Vyper, if it still exists, allows/allowed this.
--
Barnabas T. Rumjuggler
The women come and go,
Speaking of the Regis Philbin Show
-- Joe Frank
> (Though using
> commas as decimal-points is even more brain-damaged than using
> periods, which just shocks me -- what's that about fine European
> design again? ;)
but using point as decimal _separator_ is definitly strange.
;-)
--
"La vie est une école où les leçons coûtent cher, mais c'est la seule
où les insensés puissent s'instruire."
- Kipling cité par Bernard Hallé
Ah, definitely -- for example, in Italian, "false" is the plural
feminine form of the adjective "falso" (same root as English
"false", of course). Seems a rather natural name, being plural,
for some kind of collection or count of 'false-things'.
> but no we're not really talking major amounts of code... Or?)
Maybe not; then again, I see nothing "foolish" in using a
different language than English for variable-names, in code
that is not meant to be maintained by English speakers.
Alex
Indeed. That's one "feature" of C that Python
should definitely NOT have imitated!
--
Greg Ewing, Computer Science Dept, University of Canterbury,
Christchurch, New Zealand
To get my email address, please visit my web page:
http://www.cosc.canterbury.ac.nz/~greg
I do remember a letter to the editor in CACM a few
years ago complaining about all the CS oriented computer
science languages which didn't have a very useful
feature in COBOL - a data type which understood that
leading zeros are important for identifier numbers.
Eg, 04/03/01 as a date or 001-453-23264 as a part
number.
But that's neither here nor there, and since the thread
in CACM went nowhere over several months of agumentative
debate, perhaps I shouldn't have brought it up here.
So, umm, what do you think of Riemann-Stiljes integration
as it pertains to mark&sweep garbage collection of boxed
integers? How does that compare to Knuth's view? And
what if the cosmological constant is positive?
(Phew - swerved that conversation just in time!)
Andrew
da...@acm.org
> I do remember a letter to the editor in CACM a few
> years ago complaining about all the CS oriented computer
> science languages which didn't have a very useful
> feature in COBOL - a data type which understood that
> leading zeros are important for identifier numbers.
> Eg, 04/03/01 as a date or 001-453-23264 as a part
> number.
Eh? There already is a perfectly good data type for that -- a string.
--
Erik Max Francis / m...@alcyone.com / http://www.alcyone.com/max/
__ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE
/ \ The public is a fool.
\__/ Alexander Pope
Crank Dot Net / http://www.crank.net/
Cranks, crackpots, kooks, & loons on the Net.
[Andrew Dalke]
> I do remember a letter to the editor in CACM
You shouldn't read that. CACM has become the National Enquirer of
comp.lang.python wannabes.
> a few years ago
Ah, OK -- nevermind. Just be sure you don't do it again.
> complaining about all the CS oriented computer science languages
> which didn't have a very useful feature in COBOL - a data type
> which understood that leading zeros are important for identifier
> numbers. Eg, 04/03/01 as a date or 001-453-23264 as a part number.
Hmm. 04/03/01 sure looks like 4/3 to me! What's the matter with strings?
They don't automagically have a "field" concept, or automagically verify that
assignments to fields contain data of the proper form, that's what. But it's
easy enough to write a Python factory function to produce classes with those
abilities, given a format description string (call it, oh, "picture").
OTOH, trailing zeroes can be useful in real-world arithmetic, and the REXX
language defines (e.g.) 4.73 - 1.03 to be 3.70, not 3.7, and way not
3.7000000000000002. I'm going to inflict that on Python someday.
> But that's neither here nor there, and since the thread
> in CACM went nowhere over several months of agumentative
> debate, perhaps I shouldn't have brought it up here.
Na, we routinely settle debates in one arrogant msg here that the trade rags
can't resolve in a decade. Just another part of c.l.py's job.
> So, umm, what do you think of Riemann-Stiljes integration
> as it pertains to mark&sweep garbage collection of boxed
> integers?
If you view time as the horizontal axis and bytes of boxed integers reclaimed
per instant as the vertical, the area under "the curve" is the cumulative
boxed-byte-seconds (BBS) reclaimed. The connection to R-S integration is
thus immediate, as "the curve" is really a discontinuous step function.
> How does that compare to Knuth's view?
Uncle Don and I have never disagreed on this point! Don't go looking to stir
up trouble, Andrew. If you must, join me in complaining about his C coding
style. Like:
t=TT-1; while (t) {
for (j=KK-1;j>0;j--) ul[j+j]=ul[j],u[j+j]=u[j]; /* "square" */
for (j=KK+KK-2;j>KK-LL;j-=2)
ul[KK+KK-1-j]=0.0,u[KK+KK-1-j]=u[j]-ul[j];
for (j=KK+KK-2;j>=KK;j--) if(ul[j]) {
ul[j-(KK-LL)]=ulp-ul[j-(KK-LL)],
u[j-(KK-LL)]=mod_sum(u[j-(KK-LL)],u[j]);
ul[j-KK]=ulp-ul[j-KK],u[j-KK]=mod_sum(u[j-KK],u[j]);
}
if (is_odd(s)) { /* "multiply by z" */
for (j=KK;j>0;j--) ul[j]=ul[j-1],u[j]=u[j-1];
ul[0]=ul[KK],u[0]=u[KK]; /* shift the buffer cyclically */
if (ul[KK]) ul[LL]=ulp-ul[LL],u[LL]=mod_sum(u[LL],u[KK]);
}
if (s) s>>=1; else t--;
}
for (j=0;j<LL;j++) ran_u[j+KK-LL]=u[j];
for (;j<KK;j++) ran_u[j-LL]=u[j];
taken from an especially impenetrable section of
http://www-cs-staff.stanford.edu/~uno/programs/rng-double.c
Time to rewrite the TAoCP series in Python, yes?
> And what if the cosmological constant is positive?
It appears that Perl 6 is determined to test that empirically.
> (Phew - swerved that conversation just in time!)
failing-to-see-the-connection-to-transfinite-cardinals-ly y'rs - tim
so-perhaps-i-am-a-dummy-after-all-ly y'rs - steve
| > How does that compare to Knuth's view?
|
| Uncle Don and I have never disagreed on this point! Don't go looking to stir
| up trouble, Andrew. If you must, join me in complaining about his C coding
| style. Like:
|
| t=TT-1; while (t) {
| for (j=KK-1;j>0;j--) ul[j+j]=ul[j],u[j+j]=u[j]; /* "square" */
| for (j=KK+KK-2;j>KK-LL;j-=2)
| ul[KK+KK-1-j]=0.0,u[KK+KK-1-j]=u[j]-ul[j];
|
| [...]
|
| taken from an especially impenetrable section of
|
| http://www-cs-staff.stanford.edu/~uno/programs/rng-double.c
|
| Time to rewrite the TAoCP series in Python, yes?
Aw, that's not really fair, given that he does all his programming in
CWEB these days, for better or worse, and this is in straight C just
so other people can grab it easily.
Knuth's coding style is kind of historical at this point, and is
emulated at one's peril, but I learned an immense amount by reading
through the TeX source code.
Waiting for MIXAL to become whitespace-significant,
Dan
>OTOH, trailing zeroes can be useful in real-world arithmetic, and the REXX
>language defines (e.g.) 4.73 - 1.03 to be 3.70, not 3.7, and way not
>3.7000000000000002. I'm going to inflict that on Python someday.
Geez, like we don't have enough confused FP users today.
I can just imagine the postings:
Why does 1.12345678 * 3 == 3 ?
--
Grant Edwards grante Yow! Send your questions
at to "ASK ZIPPY", Box 40474,
visi.com San Francisco, CA 94140,
USA
> However, the broader issue is of a separate boolean type used for all
> logical operations. I personally think it's quite messy and confusing
> that any value has an associated logical value (e.g. 0 is false, any
> other integer is true, "" is false, any other string is true, etc.).
> But
> as I said in my previous posting, it's a widely used construct that
> doesn't seem to screw up languages too badly. And there's no way to
> change this in Python without breaking tons of code.
This is true. I would be mollified if there were a builtin operator
that tests truth in the same way that if ...: does. It would be named
something like bool or boolean and would return a 0 or 1 and nothing
else:
>>> bool(0)
0
>>> bool(3)
1
>>> bool('hello')
1
>>> bool('')
0
>>> bool([])
0
>>> bool([1])
1
>>> bool(None)
0
I'm actually surprised nothing like that already exists in the language
(maybe it does and I'm just missing it), since being able to test for
truth in the same way that if ...: would seem a common application.
That at least makes the conditional operator workaround somewhat less
ugly:
[a, b][bool(x)]
> Regarding your boolean class, could you explain the value to adding
> "don't know" to it? I can imagine it has its uses, but it sounds like
> a
> different problem domain than standard conditional logic such as
> if/then/else. If you're aiming for fuzz logic then presumably you'd
> want
> more choices than simply true, false and don't know.
Agreed, it has limited application, so limited in fact that someone
needing such behavior (true, false, don't know) would be better off
writing their own Boolean type that behaved the way they wanted.
--
Erik Max Francis / m...@alcyone.com / http://www.alcyone.com/max/
__ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE
/ \ All the people in her neighborhood turn around and get mad and sing
\__/ Public Enemy
Alcyone Systems' CatCam / http://www.catcam.com/
What do your pets do all day while you're at work? Find out.
> This is true. I would be mollified if there were a builtin operator
> that tests truth in the same way that if ...: does. It would be named
> something like bool or boolean and would return a 0 or 1 and nothing
> else:
There is a function "truth" in the operator module that does exactly
that; you could put a 'from operator import truth' in site.py, I suppose.
def bool(x):
if x: return 1
else: return 0
You can omit the "else: " for brevity, if you like. Since you seem to be
quoting interpreter output, you obviously wrote an equivalent function
yourself. However, you have no need to...
> I'm actually surprised nothing like that already exists in the language
> (maybe it does and I'm just missing it), since being able to test for
> truth in the same way that if ...: would seem a common application.
>
...since operator.truth() already does it. See, the time machine flies into
action yet again! Guido *knew* you would want this. Can we take it you are
mollified?
>>> import operator
>>> bool = operator.truth
>>> bool(0)
0
>>> bool(3)
1
>>> bool('hello')
1
>>> bool('')
0
>>> bool([])
0
>>> bool([1])
1
>>> bool(None)
0
> That at least makes the conditional operator workaround somewhat less
> ugly:
>
> [a, b][bool(x)]
>
I believe it has now been pointed out several times that this would*not* be
equivalent to the C conditional operator, because it evaluates both
expressions before selecting them according to the truth value. Close, but
no cigar.
> > Regarding your boolean class, could you explain the value to adding
> > "don't know" to it? I can imagine it has its uses, but it sounds like
> > a
> > different problem domain than standard conditional logic such as
> > if/then/else. If you're aiming for fuzz logic then presumably you'd
> > want
> > more choices than simply true, false and don't know.
>
> Agreed, it has limited application, so limited in fact that someone
> needing such behavior (true, false, don't know) would be better off
> writing their own Boolean type that behaved the way they wanted.
>
Anyone who has messed around with multi-valued logics (even the three-valued
TRUE, FALSE, NULL of SQL) will tell you that you had better sharpen your
mind before you tangle with them. The law of the divided middle is so
ensconced in most people's thinking that it's *very* difficult to chop
N-valued logic where N>2.
and-what-about-an-if:-then:-maybe:-perhaps:-sometimes:-frequently:-else:-sta
tement-ly y'rs -steve
>>> from operator import truth
>>> truth(0)
0
>>> truth(3)
1
>>> truth('hello')
1
>>> truth('')
0
>>> truth([])
0
>>> truth([1])
1
>>> truth(None)
0
>>> print truth.__doc__
truth(a) -- Return 1 if a is true, and 0 otherwise.
Cheers /F
> > I'm actually surprised nothing like that already exists in the
> > language
> > (maybe it does and I'm just missing it), since being able to test
> > for
> > truth in the same way that if ...: would seem a common application.
>
> ...since operator.truth() already does it. See, the time machine flies
> into
> action yet again! Guido *knew* you would want this. Can we take it you
> are
> mollified?
Well, there you go. I said maybe it was there and I was missing it.
> I believe it has now been pointed out several times that this
> would*not* be
> equivalent to the C conditional operator, because it evaluates both
> expressions before selecting them according to the truth value. Close,
> but
> no cigar.
Yes, that's true. It's certainly good enough for most purposes, though,
where either the expressions don't have side effects or if they do you
expect them both to be evaluated anyway. I primarily wanted to use the
functional for switching between simple values, viz.:
print "The flag is %s" % ['false', 'true'][bool(flag)]
> Anyone who has messed around with multi-valued logics (even the
> three-valued
> TRUE, FALSE, NULL of SQL) will tell you that you had better sharpen
> your
> mind before you tangle with them. The law of the divided middle is so
> ensconced in most people's thinking that it's *very* difficult to chop
> N-valued logic where N>2.
Sure. Another reason why there's no reason for it to be included in the
language proper.
--
Erik Max Francis / m...@alcyone.com / http://www.alcyone.com/max/
__ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE
/ \ 'Tis man's to fight, but Heaven's to give success.
\__/ Homer
[Grant Edwards]
> Geez, like we don't have enough confused FP users today.
> I can just imagine the postings:
>
> Why does 1.12345678 * 3 == 3 ?
It wouldn't. Read the spec, if you care:
http://www2.hursley.ibm.com/decimal/
You think?
gotta-get-my-<wink>-key-repaired-ly y'rs - tim
This works as long as trueval and falseval do not have
side-effects. As you point out, this doesn't short-circut.
>>> def x():
... print "x"
... return "x"
...
>>> def y():
... print "y"
... return "y"
...
>>> def cond(test,tv,fv):
... if test:
... return tv
... else:
... return fv
...
>>> cond(0,x(),y())
x
y
'y'
>>> (0 and [x()] or [y()])[0]
y
'y'
It's called operator.truth
--
"I'll be ex-DPL soon anyway so I'm |LUKE: Is Perl better than Python?
looking for someplace else to grab power."|YODA: No...no... no. Quicker,
-- Wichert Akkerman (on debian-private)| easier, more seductive.
For public key, finger mos...@debian.org |http://www.{python,debian,gnu}.org
y(u[KK])!