473,778 Members | 1,761 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Proposal: function which simulates C ?: operator

I think a function similar to the one below should be added to the
builtin module:

def boolselect(cond ition, trueresult, falseresult):
if condition:
return trueresult
else:
return falseresult

--- WITH

scalewidth = boolselect(self .__vertical, _scalew, _scaleh)

a1 = 0
a4 = boolselect(self .__vertical, self.__width, self.__height)
a2 = (a4 - scalewidth) // 2
a3 = a2 + scalewidth

self.__meterwid th = self.__meterrec t[0].Width()
self.__meterhei ght = self.__meterrec t[0].Height()
self.__meterlen gth = boolselect(self .__vertical, self.__meterhei ght, self.__meterwid th)

t = boolselect(self .__range >= 18, -18, -12)
redzone = self.__dBToOffs et(-6)
yellowzone = self.__dBToOffs et(t)

--- WITHOUT

if self.__vertical :
scalewidth = _scalew
else:
scalewidth = _scaleh

a1 = 0
if self.__vertical :
a4 = self.__width
else:
a4 = self.__height
a2 = (a4 - scalewidth) // 2
a3 = a2 + scalewidth

self.__meterwid th = self.__meterrec t[0].Width()
self.__meterhei ght = self.__meterrec t[0].Height()
if self.__vertical :
self.__meterlen gth = self.__meterhei ght
else:
self.__meterlen gth = self.__meterwid th

if self.__range >= 18:
t = -18
else:
t = -12
redzone = self.__dBToOffs et(-6)
yellowzone = self.__dBToOffs et(t)

---

What do you think?

PS: maybe a better name than boolselect could be found.

Jul 18 '05 #1
15 1486
Adal Chiriliuc <me@spammers.co m>
(news:13******* *************** *@smtp.myrealbo x.com) wrote:
I think a function similar to the one below should be
added to the
builtin module:

def boolselect(cond ition, trueresult, falseresult):
if condition:
return trueresult
else:
return falseresult

--- WITH

scalewidth = boolselect(self .__vertical, _scalew, _scaleh)

--- WITHOUT

if self.__vertical :
scalewidth = _scalew
else:
scalewidth = _scaleh What do you think?


Here's a nifty workaround I figured out myself but am sure others use it as
well:
scalewidth=(_sc aleh,_scalew)[__self.vertical]

HTH

It's not as readable as the "if cond ? true_expr : false_expr", but I think
introducing syntax like this is far from needed and pretty complicated.
Jul 18 '05 #2
In article <13************ ***********@smt p.myrealbox.com >,
Adal Chiriliuc <me@spammers.co m> wrote:
I think a function similar to the one below should be added to the
builtin module:

def boolselect(cond ition, trueresult, falseresult):
if condition:
return trueresult
else:
return falseresult

[ ... ]
What do you think?

PS: maybe a better name than boolselect could be found.


Some poeple might be disturbed by what it would do with

this_line = boolselect (dummy_flag, "Dummy line\n", infile.readline ())

Side-effects are the main reason that a simple function
can't generally replace a full conditional ternary operator.
See google for the ternary operator debate, and see the other
discussion in clp right now.

Regards. Mel.
Jul 18 '05 #3
Adal Chiriliuc <me@spammers.co m> writes:
I think a function similar to the one below should be added to the
builtin module:

def boolselect(cond ition, trueresult, falseresult):
if condition:
return trueresult
else:
return falseresult


That doesn't work because both results get evaluated either way. E.g.

boolselect(x==0 , f(x), g(x))

calls both f and g. You need something like

(lambda: g(x), lambda: f(x))[bool(condition)]()
Jul 18 '05 #4
Adal Chiriliuc wrote:
I think a function similar to the one below should be added to the
builtin module:

def boolselect(cond ition, trueresult, falseresult):
if condition:
return trueresult
else:
return falseresult


This doesn't simulate the conditional operator; it doesn't do
short-circuiting. See PEP 308; this kind of construct was explicitly
rejected (but then, so is the whole PEP).

--
__ Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
/ \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
\__/ Forever we / Infinitely
-- Sandra St. Victor
Jul 18 '05 #5
Paul Rubin <http://ph****@NOSPAM.i nvalid> writes:
(lambda: g(x), lambda: f(x))[bool(condition)]()


Since you call the object afterwards, you don't need the lambdas
(which add a layer of indirection), just the function references:

(g, f)[bool(condition)]()
Jul 18 '05 #6
Tor Iver Wilhelmsen wrote:
Paul Rubin <http://ph****@NOSPAM.i nvalid> writes:
(lambda: g(x), lambda: f(x))[bool(condition)]()


Since you call the object afterwards, you don't need the lambdas
(which add a layer of indirection), just the function references:

(g, f)[bool(condition)]()


Well, you meant:

(g, f)[bool(condition)](x)

but that was taking his example too literally; he was just using f(x)
and g(x) to expressions that you wanted laziy evaluated.

--
__ Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
/ \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
\__/ Forever we / Infinitely
-- Sandra St. Victor
Jul 18 '05 #7
Tor Iver Wilhelmsen <to************ *****@broadpark .no> writes:
(lambda: g(x), lambda: f(x))[bool(condition)]()


Since you call the object afterwards, you don't need the lambdas
(which add a layer of indirection), just the function references:

(g, f)[bool(condition)]()


Good catch, for that particular example. The lambdas are needed for
more general cases, e.g. (x > 0 ? (f(x)+g(y)) : (h(x)-z(y)))

There's been various proposals floated for macros in Python. If
something like that becomes real, that can solve this whole problem.

Jul 18 '05 #8
I didn't know this was discussed so much in the past. I should have
searched before.

Most of you objected that this is a bad solution because it evaluates
both variants. That's true if you want a real ternary operator. I now
think I gave a bad title to this thread. It shouldn't have mentioned
?:

I've searched through the C++ sources I'm now porting to Python
(450 KB) and found 44 uses of ?: and from these only 4 needed short
circuit evaluation (to avoid dereferencing NULL pointers or zero
division).

I now suggest that this function be added without implying that it's
the Python equivalent of ?: and with the docs clearly explaining that
it's not ?: and how it differs. It will be like Python private vars,
almost but not quite (of course, Python private vars are a lot more
close to the ideal than this is).

Anyway, I suggested this because the function I have is actually named
Util.BoolSelect , and this is kind of long :)

Jul 18 '05 #9
Adal Chiriliuc wrote:
I didn't know this was discussed so much in the past. I should have
searched before.
And if you read all of it, you probably wouldn't be making
the following suggestion, either. :-)
I now suggest that this function be added without implying that it's
the Python equivalent of ?: and with the docs clearly explaining that
it's not ?: and how it differs.


It won't happen because (a) it's a trivial function to write
on-demand, and (b) there are already several different ways of
spelling it with current Python syntax if you don't want a
function, and (c) I suspect that the requirement for short-circuit
evaluation would actually be *more* common in Python than it
appears it is in C++ based on your very limited sample population.

-Peter
Jul 18 '05 #10

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

Similar topics

2
1708
by: Guido van Rossum | last post by:
Robert and Python-dev, I've read the J2 proposal up and down several times, pondered all the issues, and slept on it for a night, and I still don't like it enough to accept it. The only reason to accept it would be to pacify the supporters of the proposal, and that just isn't a good enough reason in language design. However, it got pretty darn close! I'm impressed with how the community managed to pull together and face the enormous...
31
2442
by: Brian Sabbey | last post by:
Here is a pre-PEP for what I call "suite-based keyword arguments". The mechanism described here is intended to act as a complement to thunks. Please let me know what you think. Suite-Based Keyword Arguments ----------------------------- Passing complicated arguments to functions is currently awkward in Python. For example, the typical way to define a class property winds up polluting the class's namespace with the property's get/set...
59
3946
by: seberino | last post by:
I've heard 2 people complain that word 'global' is confusing. Perhaps 'modulescope' or 'module' would be better? Am I the first peope to have thought of this and suggested it? Is this a candidate for Python 3000 yet? Chris
4
2737
by: wkaras | last post by:
I would like to propose the following changes to the C++ Standard, the goal of which are to provide an improved ability to specify the constraints on type parameters to templates. Let me say from the start that my knowledge of compiler implementation is very limited. Therefore, my suggestions may have to be rejected because they are difficult or impossible to implement. The proposal is based on the concept of "type similarity". Type...
17
2444
by: Steve R. Hastings | last post by:
I have been studying Python recently, and I read a comment on one web page that said something like "the people using Python for heavy math really wish they could define their own operators". The specific example was to define an "outer product" operator for matrices. (There was even a PEP, number 211, about this.) I gave it some thought, and Googled for previous discussions about this, and came up with this suggestion: User-defined...
23
5335
by: Kaz Kylheku | last post by:
I've been reading the recent cross-posted flamewar, and read Guido's article where he posits that embedding multi-line lambdas in expressions is an unsolvable puzzle. So for the last 15 minutes I applied myself to this problem and come up with this off-the-wall proposal for you people. Perhaps this idea has been proposed before, I don't know. The solutions I have seen all assume that the lambda must be completely inlined within the...
34
1883
by: glomde | last post by:
i I would like to extend python so that you could create hiercical tree structures (XML, HTML etc) easier and that resulting code would be more readable than how you write today with packages like elementtree and xist. I dont want to replace the packages but the packages could be used with the new operators and the resulting IMHO is much more readable. The syntax i would like is something like the below:
10
3310
by: =?iso-8859-2?B?SmFuIFJpbmdvuQ==?= | last post by:
Hello everybody, this is my first post to a newsgroup at all. I would like to get some feedback on one proposal I am thinking about: --- begin of proposal --- Proposal to add signed/unsigned modifier to class declarations to next revision of C++ programming language
0
1667
by: terminator | last post by:
first: I find the 'r/l-value reference' terminology rather confusing and I find the following names for this new refrence type more suitable: temporary reference: Since it is generally intended to refere to temporary objects Immidiate referenc: Since literals are assumed as temporary in C++ and immidiate or quick in assembly language.
0
9464
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
10292
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
10122
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10061
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9923
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
6722
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
5368
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5497
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3627
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.