Short if

  • Thread starter Thomas Lindgaard
  • Start date
T

Thomas Lindgaard

Hello

Does Python have a short if like C or PHP:

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

?
 
V

vincent wehren

Thomas said:
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.python.org/peps/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').
 
P

Paul Sweeney

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!
 
P

Peter Hickman

Thomas said:
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.
 
S

Sylvain Thenault

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')
 
R

Reinhold Birkenfeld

Sylvain said:
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
 
T

Thomas Lindgaard

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.
 
D

Duncan Booth

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'
 
S

Sylvain Thenault

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.
 
V

Vincent Wehren

Newsbeitrag
| 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
|
 
P

Peter Hansen

Reinhold said:
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
 
S

Steve Holden

Vincent said:
Newsbeitrag
| 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
 
H

Heather Coppersmith

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
 
D

David Bolen

Steve Holden said:
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
 
P

Peter Hansen

David said:
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
 
T

Tor Iver Wilhelmsen

Thomas Lindgaard said:
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.)
 
R

Reinhold Birkenfeld

Peter said:
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
 
P

Peter Hansen

Reinhold said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,202
Messages
2,571,057
Members
47,661
Latest member
sxarexu

Latest Threads

Top