473,799 Members | 3,149 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Most compact "X if X else Y" idiom

I find myself having to do the following:

x = (some complex expression)
y = x if x else "blah"

and I was wondering if there is any built-in idiom that
can remove the need to put (some complex expression)
in the temporary variable x.

e.g. something like the below:

y= foobar ((some complex expression), "blah")

I realized foobar() can be easily coded as:
def foobar(a,b):
if a: return a
else: return b

But I was wondering if there was a built-in function or syntax
that already does this.
Oct 12 '08 #1
5 3818
On Oct 12, 12:01*am, jbperez...@yaho o.com wrote:
I find myself having to do the following:

* x = (some complex expression)
* y = x if x else "blah"

and I was wondering if there is any built-in idiom that
can remove the need to put (some complex expression)
in the temporary variable x.

e.g. something like the below:

*y= foobar ((some complex expression), "blah")

I realized foobar() can be easily coded as:
* def foobar(a,b):
* * if a: return a
* * else: return b

But I was wondering if there was a built-in function or syntax
that already does this.
You could take your chances on 'or', as follows:
>>(6+ (3<< 1) ) or 'blah'
12
>>(6- (3<< 1) ) or 'blah'
'blah'

You don't need to use the ternary statement:

y = (some complex expression)
if not y:
y = "blah"

If you find yourself using it a lot, why not add it to your site's
utilities modules? Take your time, and if you find numerous uses,
present them and make the case Python should have a built-in to do it,
something like 'ditto' marks:

(6- (3<< 1) ) if ditto else 'blah'

Oct 12 '08 #2
jb********@yaho o.com wrote:
I find myself having to do the following:

x = (some complex expression)
y = x if x else "blah"

and I was wondering if there is any built-in idiom that
can remove the need to put (some complex expression)
in the temporary variable x.
A common idiom for this particular case where the if-expression is also
the conditional or the basic of the conditional expression is

y = <some complex expression>
if not y: y = "blah"

Oct 12 '08 #3
On Sat, 11 Oct 2008 22:01:46 -0700, jbperez808 wrote:
I find myself having to do the following:

x = (some complex expression)
y = x if x else "blah"

and I was wondering if there is any built-in idiom that can remove the
need to put (some complex expression) in the temporary variable x.
Use short-circuit Booleans:

y = x or "blah"

If x is any true value (non-zero number, non-empty string etc.) then y
will be set to x; but if x is any false value (zero, empty string, None,
empty list, etc.) then y will be set to "blah".
However, this technique doesn't work for arbitrary tests. For example,
you can't simplify the following:

x = (some complex expression)
y = x if 100<=x<250 else "blah"

(at least I can't think of any way).

--
Steven
Oct 12 '08 #4
On Sun, 12 Oct 2008 05:30:33 +0000, Steven D'Aprano wrote:
Use short-circuit Booleans:

y = x or "blah"
Except of course you don't use x, you use the complex expression.

y = (some complex expression) or "blah"

Sorry for the itchy posting finger.

--
Steven
Oct 12 '08 #5
Thanks, folks.

Short-circuit boolean was the syntax I had in mind which
momentarily escaped me, but the "if not x: x='blah'" idiom
was instructive as well.
Oct 12 '08 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

23
3583
by: Invalid User | last post by:
While trying to print a none empty list, I accidentaly put an "else" statement with a "for" instead of "if". Here is what I had: if ( len(mylist)> 0) : for x,y in mylist: print x,y else: print "Empty list" which was supposed to be:
11
2174
by: David Morgenthaler | last post by:
How does one overide the iterator implied by the construct "for line in file:"? For example, suppose I have a file containing row,col pairs on each line, and I wish to write a subclass of file that will transform these to x,y coordinates using an affine transform. I'd like it to look something like this (but this clearly doesn't work): class myFile(file): def __init__(self,name,affine):
40
3050
by: Steve Juranich | last post by:
I know that this topic has the potential for blowing up in my face, but I can't help asking. I've been using Python since 1.5.1, so I'm not what you'd call a "n00b". I dutifully evangelize on the goodness of Python whenever I talk with fellow developers, but I always hit a snag when it comes to discussing the finer points of the execution model (specifically, exceptions). Without fail, when I start talking with some of the "old-timers"...
5
5236
by: Prakash | last post by:
Does anyone know how to compact a table (only) ? I'm using some code o move rows up & down in a continuous form & it works fine, but after some usage the rows refuse to move up or down until I compact the database. Then with no modifications to the code it works well. Any ideas anyone ? Thx & Best Rgds,
81
7358
by: Matt | last post by:
I have 2 questions: 1. strlen returns an unsigned (size_t) quantity. Why is an unsigned value more approprate than a signed value? Why is unsighned value less appropriate? 2. Would there be any advantage in having strcat and strcpy return a pointer to the "end" of the destination string rather than returning a
28
2859
by: Jess | last post by:
Hello, It is said that if I implement a "swap" member function, then it should never throw any exception. However, if I implement "swap" non- member function, then the restriction doesn't apply. Can somebody tell me why? Thanks, Jess
4
9864
by: FullBandwidth | last post by:
I have been perusing various blogs and MSDN pages discussing the use of event properties and the EventHandlerList class. I don't believe there's anything special about the EventHandlerList class in this context, in fact some articles from pre-2.0 suggest using any collection class of your choice. So my questions focus more on the syntax of event properties provided by the "event" keyword in C#. (Disclaimer - I am a C++ programmer working...
6
2408
by: .rhavin grobert | last post by:
hello;-) i frequently need the following construction: ReturnParam § Function() § { /...do something.../ someType var § = something; /...do something.../ return something;
5
371
by: Joe Strout | last post by:
On Nov 13, 2008, at 10:19 AM, Chris Mellon wrote: Argh. I've been back in the Python community for about a month, and I've been continually amazed at how every single "how do I do X" or "what do you think of this method of doing X" question is answered by people on high horses claiming "you shouldn't do X". I know very well about state and objects. I'll be happy to whip out my software engineering credentials and measure them...
0
9687
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9541
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10484
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10027
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9072
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6805
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5585
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3759
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2938
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.