470,849 Members | 859 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 470,849 developers. It's quick & easy.

Short if

Hello

Does Python have a short if like C or PHP:

bool = false
string = 'This is ' + (( bool ) ? 'true' : 'false')

?

--
Mvh.
/Thomas

Jul 18 '05 #1
24 3089
* Thomas Lindgaard <th****@it-snedkeren.BLACK_HOLE.dk>
in comp.lang.python:
Does Python have a short if like C or PHP:


<http://www.python.org/doc/faq/programming.html#is-there-an-equivalent-of-c-s-ternary-operator>

--
DW
Jul 18 '05 #2
Damien Wyart wrote:
* Thomas Lindgaard <th****@it-snedkeren.BLACK_HOLE.dk>
in comp.lang.python:
Does Python have a short if like C or PHP:


<http://www.python.org/doc/faq/programming.html#is-there-an-equivalent-of-c-s-ternary-operator>


Is the reject of this feature final? I mean, is discussion about the
construct obsolete?

Reinhold

--
Wenn eine Linuxdistribution so wenig brauchbare Software wie Windows
mitbrächte, wäre das bedauerlich. Was bei Windows der Umfang eines
"kompletten Betriebssystems" ist, nennt man bei Linux eine Rescuedisk.
-- David Kastrup in de.comp.os.unix.linux.misc
Jul 18 '05 #3
Thomas Lindgaard wrote:
Hello

Does Python have a short if like C or PHP:

bool = false
string = 'This is ' + (( bool ) ? 'true' : 'false')

?


Nope. PEP308 to introduce a ternary operator like idiom has been
rejected (see:
http://www.sourcekeg.co.uk/www.pytho...pep-0308.html),
but you can emulate it:
bool = False
s = "This is " + ('false', 'true')[bool]
print s

This is false

In this case bool evaluates to 0 and 'false' is at index 0 of the tuple
('false', 'true').

--
Vincent Wehren
Jul 18 '05 #4
> Does Python have a short if like C or PHP:

bool = false
string = 'This is ' + (( bool ) ? 'true' : 'false')

If you are really convinced that this is a good road to go down (think of
code readability), you could do

bool = False # check capitalisation!
string = 'This is ' + ('false','true')[bool]

I never liked the C ? operator, always finding code was clearer using the
full if, and this hack is even worse!
Jul 18 '05 #5
Thomas Lindgaard wrote:
Hello

Does Python have a short if like C or PHP:

bool = false
string = 'This is ' + (( bool ) ? 'true' : 'false')

?


As elegant as that may seem it is all too easy to abuse. Especially when people
start to nest them. Code can quickly become unreadable. I almost always have to
convert nested ?:'s to proper if then else constructs when I come across them in
Perl.

But then I prefer readability over byte misering. Python is a language which is
founded on readability, lets not forget that.
Jul 18 '05 #6
On Wed, 07 Jul 2004 09:40:04 +0000, Paul Sweeney wrote:
Does Python have a short if like C or PHP:

bool = false
string = 'This is ' + (( bool ) ? 'true' : 'false')


If you are really convinced that this is a good road to go down (think of
code readability), you could do

bool = False # check capitalisation! string = 'This is ' +
('false','true')[bool]


you can use logical "and" and "or" to achieve this:

string = 'This is ' + (bool and 'true' or 'false')

--
Sylvain Thénault LOGILAB, Paris (France).

http://www.logilab.com http://www.logilab.fr http://www.logilab.org
Jul 18 '05 #7
Sylvain Thenault wrote:
On Wed, 07 Jul 2004 09:40:04 +0000, Paul Sweeney wrote:
Does Python have a short if like C or PHP:

bool = false
string = 'This is ' + (( bool ) ? 'true' : 'false')


If you are really convinced that this is a good road to go down (think of
code readability), you could do

bool = False # check capitalisation! string = 'This is ' +
('false','true')[bool]


you can use logical "and" and "or" to achieve this:

string = 'This is ' + (bool and 'true' or 'false')


But be warned, if you construct such a thing:

int = 2 + (bool and 0 or 1)

you will get 3 as an answer every time. So if you want to use the
and-or-Form, be sure that the second expression cannot have a false
value (that is, "", [], {}, 0, etc.)

Reinhold

--
Wenn eine Linuxdistribution so wenig brauchbare Software wie Windows
mitbrächte, wäre das bedauerlich. Was bei Windows der Umfang eines
"kompletten Betriebssystems" ist, nennt man bei Linux eine Rescuedisk.
-- David Kastrup in de.comp.os.unix.linux.misc
Jul 18 '05 #8
On Wed, 07 Jul 2004 11:14:45 +0200, Thomas Lindgaard wrote:
Hello

Does Python have a short if like C or PHP:

bool = false
string = 'This is ' + (( bool ) ? 'true' : 'false')

?


Ok, I see that this is not really the language for short ifs (writing
('true', 'false')[bool] does not strike me as being very readable, so I
think I'll revert to the long version).

Used carefully, though, I think that the ternary operator is very useful.

--
Regards
/Thomas

Jul 18 '05 #9
Thomas Lindgaard <th****@it-snedkeren.BLACK_HOLE.dk> wrote in
news:pa****************************@it-snedkeren.BLACK_HOLE.dk:
bool = false
string = 'This is ' + (( bool ) ? 'true' : 'false')


You don't actually need a conditional expression here at all:

aBool = False
string = 'This is ' + str(aBool)

sets string to 'This is False'
Jul 18 '05 #10

"Thomas Lindgaard" <th****@it-snedkeren.BLACK_HOLE.dk> schrieb im
Newsbeitrag
news:pa****************************@it-snedkeren.BLACK_HOLE.dk...
| On Wed, 07 Jul 2004 11:14:45 +0200, Thomas Lindgaard wrote:
|
| > Hello
| >
| > Does Python have a short if like C or PHP:
| >
| > bool = false
| > string = 'This is ' + (( bool ) ? 'true' : 'false')
| >
| > ?
|
| Ok, I see that this is not really the language for short ifs (writing
| ('true', 'false')[bool] does not strike me as being very readable, so I
| think I'll revert to the long version).

The readability concern is justified. Still, I find myself using this style
a lot, especially in situations such as:

class Klass:
def __init__(self, a, b, foo=None, bar=None):

self.a = a
self.b = b
self.foo = (foo, someDefaultMutable)[foo is None]
self.bar = (bar, someOtherDefaultMutable)[bar is None]
I don't like putting a lot of else/if blocks in __init__, but that's just
personal taste I guess.

--
Vincent Wehren


|
| Used carefully, though, I think that the ternary operator is very useful.

|
| --
| Regards
| /Thomas
|
Jul 18 '05 #11
Reinhold Birkenfeld wrote:
Damien Wyart wrote:
<http://www.python.org/doc/faq/programming.html#is-there-an-equivalent-of-c-s-ternary-operator>


Is the reject of this feature final? I mean, is discussion about the
construct obsolete?


As the resulting thread is already showing, no, discussion
is definitely not obsolete.

Pointless, maybe, but not obsolete. ;-)

-Peter
Jul 18 '05 #12
Vincent Wehren wrote:
"Thomas Lindgaard" <th****@it-snedkeren.BLACK_HOLE.dk> schrieb im
Newsbeitrag
news:pa****************************@it-snedkeren.BLACK_HOLE.dk...
| On Wed, 07 Jul 2004 11:14:45 +0200, Thomas Lindgaard wrote:
|
| > Hello
| >
| > Does Python have a short if like C or PHP:
| >
| > bool = false
| > string = 'This is ' + (( bool ) ? 'true' : 'false')
| >
| > ?
|
| Ok, I see that this is not really the language for short ifs (writing
| ('true', 'false')[bool] does not strike me as being very readable, so I
| think I'll revert to the long version).

The readability concern is justified. Still, I find myself using this style
a lot, especially in situations such as:

class Klass:
def __init__(self, a, b, foo=None, bar=None):

self.a = a
self.b = b
self.foo = (foo, someDefaultMutable)[foo is None]
self.bar = (bar, someOtherDefaultMutable)[bar is None]
I don't like putting a lot of else/if blocks in __init__, but that's just
personal taste I guess.

I should have thought that this is about the same as

self.foo = foo or someDefaultMutable
self.bar = bar or someOTherDefaultMutable

but as you say, tastes vary. I find the latter much more readable, as I
don't have to mentally convert the Boolean to a zero or one subscript
value to realise what happens when foo *is* None.

regards
S teve
Jul 18 '05 #13
On Wed, 7 Jul 2004 15:08:38 +0200,
"Vincent Wehren" <vw*****@home.nl> wrote:
class Klass:
def __init__(self, a, b, foo=None, bar=None): self.a = a
self.b = b
self.foo = (foo, someDefaultMutable)[foo is None]
self.bar = (bar, someOtherDefaultMutable)[bar is None]


self.foo = foo or someDefaultMutable
self.bar = bar or someOtherDefaultMutable

Regards,
Heather

--
Heather Coppersmith
That's not right; that's not even wrong. -- Wolfgang Pauli
Jul 18 '05 #14
On Wed, 07 Jul 2004 12:04:11 +0000, Duncan Booth wrote:
Thomas Lindgaard <th****@it-snedkeren.BLACK_HOLE.dk> wrote in
news:pa****************************@it-snedkeren.BLACK_HOLE.dk:
bool = false
string = 'This is ' + (( bool ) ? 'true' : 'false')


You don't actually need a conditional expression here at all:

aBool = False
string = 'This is ' + str(aBool)

sets string to 'This is False'


only with python >= 2.3, where the bool type has been introduced.

--
Sylvain Thénault LOGILAB, Paris (France).

http://www.logilab.com http://www.logilab.fr http://www.logilab.org
Jul 18 '05 #15
Steve Holden <sh*****@holdenweb.com> writes:
Vincent Wehren wrote: (...)
class Klass:
def __init__(self, a, b, foo=None, bar=None):
self.a = a
self.b = b
self.foo = (foo, someDefaultMutable)[foo is None]
self.bar = (bar, someOtherDefaultMutable)[bar is None]

(...) I should have thought that this is about the same as

self.foo = foo or someDefaultMutable
self.bar = bar or someOTherDefaultMutable

but as you say, tastes vary. I find the latter much more readable, as
I don't have to mentally convert the Boolean to a zero or one
subscript value to realise what happens when foo *is* None.


Except that your code will result in using the default mutable if a
user passes in their own mutable that happens to be empty. That may
still work in some cases, but it's certainly not equivalent code. In
Vincent's example, None is a true Sentinel value (thus the "is" check)
and isn't just being used as equivalent to any false value.

Of course, this use case is really only needed due to Python's
handling of default variables (constructed once at compile time),
making it unsuitable in many cases when the default variable should be
mutable. So if there were a way to address that in a backwards
compatible manner, it would also simplify this scenario.

-- David
Jul 18 '05 #16
David Bolen wrote:
Steve Holden <sh*****@holdenweb.com> writes:
I should have thought that this is about the same as

self.foo = foo or someDefaultMutable
self.bar = bar or someOTherDefaultMutable

but as you say, tastes vary. I find the latter much more readable, as
I don't have to mentally convert the Boolean to a zero or one
subscript value to realise what happens when foo *is* None.


Except that your code will result in using the default mutable if a
user passes in their own mutable that happens to be empty. That may
still work in some cases, but it's certainly not equivalent code. In
Vincent's example, None is a true Sentinel value (thus the "is" check)
and isn't just being used as equivalent to any false value.


That is true of course, but keep in mind also that the most common
use of such patterns is actually to initialize self.foo to an
*empty* mutable of the appropriate type. In that case (and that
case alone), it is generally equivalent at least in outcome, as
if the user passes in an empty (say, list), the above code will
use the "someDefaultMutable" empty list instead, but the result
is still what was desired in most cases.

But it is good to know the distinctions, and the fact that there
are such distinctions still means that good ol' "if/else" is still
the safest way to go...

-Peter
Jul 18 '05 #17
Thomas Lindgaard <th****@it-snedkeren.BLACK_HOLE.dk> writes:
writing ('true', 'false')[bool] does not strike me as being very
readable,


.... which makes it a perfect candidate for the ?: ternary operator.

:)

(Also, if the variable "bool" can hold some non-boolean value you want
to check, use the builtin bool() function, as someone was nice to
point out to me the last time a similar question came up.)
Jul 18 '05 #18
Peter Hansen wrote:
Reinhold Birkenfeld wrote:
Damien Wyart wrote:
<http://www.python.org/doc/faq/programming.html#is-there-an-equivalent-of-c-s-ternary-operator>


Is the reject of this feature final? I mean, is discussion about the
construct obsolete?


As the resulting thread is already showing, no, discussion
is definitely not obsolete.

Pointless, maybe, but not obsolete. ;-)


That is, in a friendly way, as if one said: "Go and play, kids, but
don't expect us adults to pay attention to it" ;)

Reinhold

--
Wenn eine Linuxdistribution so wenig brauchbare Software wie Windows
mitbrächte, wäre das bedauerlich. Was bei Windows der Umfang eines
"kompletten Betriebssystems" ist, nennt man bei Linux eine Rescuedisk.
-- David Kastrup in de.comp.os.unix.linux.misc
Jul 18 '05 #19
Reinhold Birkenfeld wrote:
Peter Hansen wrote:
Reinhold Birkenfeld wrote:
Damien Wyart wrote:

<http://www.python.org/doc/faq/programming.html#is-there-an-equivalent-of-c-s-ternary-operator>

Is the reject of this feature final? I mean, is discussion about the
construct obsolete?


As the resulting thread is already showing, no, discussion
is definitely not obsolete.

Pointless, maybe, but not obsolete. ;-)


That is, in a friendly way, as if one said: "Go and play, kids, but
don't expect us adults to pay attention to it" ;)


Actually, it's nothing like that at all. I wrote about
the fact (as I see it) that further discussion will not
result in a change to the situation. I said nothing about
me or anyone else (assuming I'm in the group you refer to
as "us adults") paying attention to those who want to
discuss it further. If enough motivated people could
reach a consensus, it's possible Guido would actually relent
and put the strong majority's ternary in someday. Only
Tim can say. :-)

I used a wink, and you mentioned "friendly", so I'll assume
this should all be light-hearted and avoid taking offense that
you would try to put such condescending words in my mouth.

-Peter
Jul 18 '05 #20
Peter Hansen wrote:
Reinhold Birkenfeld wrote:
Peter Hansen wrote:
Reinhold Birkenfeld wrote:
Damien Wyart wrote:

><http://www.python.org/doc/faq/programming.html#is-there-an-equivalent-of-c-s-ternary-operator>

Is the reject of this feature final? I mean, is discussion about the
construct obsolete?

As the resulting thread is already showing, no, discussion
is definitely not obsolete.

Pointless, maybe, but not obsolete. ;-)


That is, in a friendly way, as if one said: "Go and play, kids, but
don't expect us adults to pay attention to it" ;)


Actually, it's nothing like that at all. I wrote about
the fact (as I see it) that further discussion will not
result in a change to the situation. I said nothing about
me or anyone else (assuming I'm in the group you refer to
as "us adults") paying attention to those who want to
discuss it further. If enough motivated people could
reach a consensus, it's possible Guido would actually relent
and put the strong majority's ternary in someday. Only
Tim can say. :-)

I used a wink, and you mentioned "friendly", so I'll assume
this should all be light-hearted and avoid taking offense that
you would try to put such condescending words in my mouth.


Yes, that's right. It's the spirit of the Python community, I think, and
this is a Good Thing[tm].

Reinhold

--
Wenn eine Linuxdistribution so wenig brauchbare Software wie Windows
mitbrächte, wäre das bedauerlich. Was bei Windows der Umfang eines
"kompletten Betriebssystems" ist, nennt man bei Linux eine Rescuedisk.
-- David Kastrup in de.comp.os.unix.linux.misc
Jul 18 '05 #21
Peter Hansen <pe***@engcorp.com> writes:
That is true of course, but keep in mind also that the most common
use of such patterns is actually to initialize self.foo to an
*empty* mutable of the appropriate type. In that case (and that
case alone), it is generally equivalent at least in outcome, as
if the user passes in an empty (say, list), the above code will
use the "someDefaultMutable" empty list instead, but the result
is still what was desired in most cases.
Maybe, maybe not. Using an alternate empty list is only equivalent if
the function is not supposed to mutate the supplied parameter, but is
instead, for example, returning a reference to the resultant mutable
object. (The original sample didn't include the full function so I
don't know if it was returning the reference).

Given that a mutable object is coming in as a parameter, and an
optional parameter at that, I think it's probably even odds that if it
was supplied, the function may be expected to mutate the object that
the caller supplied.
But it is good to know the distinctions, and the fact that there
are such distinctions still means that good ol' "if/else" is still
the safest way to go...


Yep.

-- David
Jul 18 '05 #22
Paul Sweeney wrote:
Does Python have a short if like C or PHP:

bool = false
string = 'This is ' + (( bool ) ? 'true' : 'false')


If you are really convinced that this is a good road to go down (think of
code readability), you could do

bool = False # check capitalisation!
string = 'This is ' + ('false','true')[bool]

I never liked the C ? operator, always finding code was clearer using the
full if, and this hack is even worse!


It's not about code readability. It's about functional programming.
Lambda expressions don't make very readable code, but Python supports
them anyway. If Python is serious about it's functional aspects, it
requires a ternary operator. Only in the context of functional
programming is this relevant, which makes the whole "it's ugly" argument
moot. Besides, a real ternary, instead of
((condition) and [truecase] or [falsecase])[0]
looks a whole lot better IMO.
Jul 18 '05 #23
"Paul Sweeney" <re*******************@nothypgnal.delrest.co.uk> writes:
bool = false
string = 'This is ' + (( bool ) ? 'true' : 'false')
If you are really convinced that this is a good road to go down (think of
code readability), you could do

bool = False # check capitalisation!
string = 'This is ' + ('false','true')[bool]


But that can easily become incorrect when the branches have side effects:

string = 'This is ' + (false(), true())[bool]

You have to do something like:

string = 'This is ' + (lambda: false(), lambda: true())[bool]()
I never liked the C ? operator, always finding code was clearer using the
full if, and this hack is even worse!


Which is more readable depends on the context. Sometimes the 'if'
just bloats up your code.
Jul 18 '05 #24
Thomas Lindgaard wrote:
Hello

Does Python have a short if like C or PHP:

bool = false
string = 'This is ' + (( bool ) ? 'true' : 'false')

?


No, thankfully! It's ugly and makes for less maintainable code IMO (as it is
effectively an inside-out if that you have to rewrite if you want to add any
more conditional code).

Jul 18 '05 #25

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

10 posts views Thread by Niels Dekker (no reply address) | last post: by
99 posts views Thread by Glen Herrmannsfeldt | last post: by
8 posts views Thread by NilsNilsson | last post: by
8 posts views Thread by Ken Dopierala Jr. | last post: by
15 posts views Thread by Steffen Loringer | last post: by
4 posts views Thread by slougheed | last post: by
10 posts views Thread by Jim Langston | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.