473,378 Members | 1,541 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,378 software developers and data experts.

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 3286
* 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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
by: Niels Dekker (no reply address) | last post by:
Is it possible for a standard compliant C++ compiler to have ( sizeof(short) < sizeof(int) ) and ( sizeof(short) == sizeof((short)0 + (short)0) ) ? Regards, Niels Dekker...
99
by: Glen Herrmannsfeldt | last post by:
I was compiling a program written by someone else about six years ago, and widely distributed at the time. It also includes makefiles for many different systems, so I know it has been compiled...
34
by: Andy | last post by:
Hi, Are 1 through 4 defined behaviors in C? unsigned short i; unsigned long li; /* 32-bit wide */ 1. i = 65535 + 3; 2. i = 1 - 3; 3. li = (unsigned long)0xFFFFFFFF + 3; 4. li = 1...
8
by: NilsNilsson | last post by:
I wrote this: short s1 = 0; short s2 = 1; short s3 = s1 + s2; And gor this compile error message: Cannot implicitly convert type 'int' to 'short' What is wrong here?
8
by: Ken Dopierala Jr. | last post by:
Hi, I'm reading the header file of a PCX image and I need to convert 2 bytes to a short. How would I go about doing this? I know that they are bytes 8 & 9 in my byte array. I'm not sure how to...
15
by: Steffen Loringer | last post by:
Hi, I'm using the following function to join 2 char (byte) into one short on a 32 bit X86 platform: unsigned short joinUnsigShort(unsigned char a,unsigned char b) { unsigned short val = 0;...
4
by: slougheed | last post by:
I encountered a problem after we had converted our declarations of 'unsigned short int' to uint16_t. In one instance, whoever did the conversion failed to delete the 'short' keyword so we had a...
10
by: Jim Langston | last post by:
Is the following well defined? size_t IntVal = 65537; unsigned short Length; if ( IntVal static_cast<unsigned short>( -1 ) ) { std::cout << "Value too long to fit in a short" << std::endl;...
10
by: nyhetsgrupper | last post by:
The following code result in the following compilation error: Error 1 Cannot implicitly convert type 'int' to 'short'. An explicit conversion exists (are you missing a cast?) short a = 1; short...
3
by: mathieu | last post by:
Could someone please tell me what is wrong with the following -ugly- piece of c++ code. Why when I explicititely set the template parameter my gcc compiler start getting confused: bla.cxx: In...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.