473,385 Members | 1,341 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,385 software developers and data experts.

Ternary operator alternative in Ptyhon

I'm sure this is a popular one, but after Googling for a while I
couldn't figure out how to pull this off.

Let's say I have this initializer on a class:

def __init__(self, **params):

I'd like to short-circuit the assignment of class field values passed in
this dictionary to something like this:

self.SomeField = \
params.has_key("mykey") ? params["mykey"] : None)

Obviously I know this is not actual Python syntax, but what would be the
equivalent? I'm trying to avoid this, basically:

if params.has_key("mykey"):
self.SomeField = params["mykey"]
else:
self.SomeField = None

This is not a big deal of course, but I guess my main goal is to try and
figure out of I'm not missing something more esoteric in the language
that lets me do this.

Thanks in advance.
Jun 27 '08 #1
7 1662
On Wednesday 18 June 2008, kretik wrote:
if params.has_key("mykey"):
self.SomeField = params["mykey"]
else:
self.SomeField = None

self.SomeField = parms.get('mykey', None)

This looks like what you want and it is also simpler because you don't deal
with checking if the key exists.
Jun 27 '08 #2
On Tue, 17 Jun 2008 23:18:51 -0700, kretik wrote:
I'm sure this is a popular one, but after Googling for a while I
couldn't figure out how to pull this off.

Let's say I have this initializer on a class:

def __init__(self, **params):
Why not ``__init__(self, mykey=None)`` in the first place?
I'd like to short-circuit the assignment of class field values passed in
this dictionary to something like this:

self.SomeField = \
params.has_key("mykey") ? params["mykey"] : None)

Obviously I know this is not actual Python syntax, but what would be the
equivalent? I'm trying to avoid this, basically:

if params.has_key("mykey"):
self.SomeField = params["mykey"]
else:
self.SomeField = None

This is not a big deal of course, but I guess my main goal is to try and
figure out of I'm not missing something more esoteric in the language
that lets me do this.

Thanks in advance.
You're lucky -- Python 2.5 just grew a ternary if-construct. You'd use it
like that::

self.SomeField = params["mykey"] if "mykey" in params else None
# or, generically: TRUE if CONDITION else FALSE

Notice the use of the `in` operator, which is recommended over
`dict.has_key`.

HTH,

--
Robert "Stargaming" Lehmann
Jun 27 '08 #3
kretik wrote:
I'm sure this is a popular one, but after Googling for a while I
couldn't figure out how to pull this off.

Let's say I have this initializer on a class:

def __init__(self, **params):

I'd like to short-circuit the assignment of class field values passed
in this dictionary to something like this:

self.SomeField = \
params.has_key("mykey") ? params["mykey"] : None)
For years, Python did not have such a thing, but recent versions support
the syntax
a if c else b

In spite of the odd ordering of that parts, they are executed (or not)
just as you like.
self.SomeField = params["mykey"] if params.has_key("mykey") else None
Gary Herron
>
Obviously I know this is not actual Python syntax, but what would be
the equivalent? I'm trying to avoid this, basically:

if params.has_key("mykey"):
self.SomeField = params["mykey"]
else:
self.SomeField = None

This is not a big deal of course, but I guess my main goal is to try
and figure out of I'm not missing something more esoteric in the
language that lets me do this.

Thanks in advance.
--
http://mail.python.org/mailman/listinfo/python-list
Jun 27 '08 #4
kretik wrote:
I'm sure this is a popular one, but after Googling for a while I
couldn't figure out how to pull this off.

Let's say I have this initializer on a class:

def __init__(self, **params):

I'd like to short-circuit the assignment of class field values passed in
this dictionary to something like this:

self.SomeField = \
params.has_key("mykey") ? params["mykey"] : None)

Obviously I know this is not actual Python syntax, but what would be the
equivalent? I'm trying to avoid this, basically:

if params.has_key("mykey"):
self.SomeField = params["mykey"]
else:
self.SomeField = None

This is not a big deal of course, but I guess my main goal is to try and
figure out of I'm not missing something more esoteric in the language
that lets me do this.

Thanks in advance.
The syntax is a bit different, but:

result = (true_value if condition else false_value)

is how it is in Pytthon:

self.SomeField = (params['mykey'] if params.has_key('mykey') else None)

Brian Vanderburg II
Jun 27 '08 #5
kretik a écrit :
I'm sure this is a popular one, but after Googling for a while I
couldn't figure out how to pull this off.

I'd like to short-circuit the assignment of class field values passed in
this dictionary to something like this:

self.SomeField = \
params.has_key("mykey") ? params["mykey"] : None)

Obviously I know this is not actual Python syntax, but what would be the
equivalent? I'm trying to avoid this, basically:

if params.has_key("mykey"):
self.SomeField = params["mykey"]
else:
self.SomeField = None

This is not a big deal of course, but I guess my main goal is to try and
figure out of I'm not missing something more esoteric in the language
that lets me do this.
You can also use :
self.SomeField = params.has_key("mykey") and params["mykey"] or None

But it's not easy to read
--
Jérémie
Jun 27 '08 #6
jeremie fouche wrote:
You can also use :
self.SomeField = params.has_key("mykey") and params["mykey"] or None
Have caution with this solution: it may not provide the desired result in
the case where params["mykey"] is a false value, such as 0, or []
Jeffrey
Jun 27 '08 #7
Thank you everyone. I ended up implementing the dict.get() method, which
seems "cleaner", but I'll keep the (x if y else z) syntax in mind. I
didn't know it existed, I guess it's what I was looking for to begin with.

Thanks again!

Allen wrote:
kretik wrote:
>I'm sure this is a popular one, but after Googling for a while I
couldn't figure out how to pull this off.
Jun 27 '08 #8

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

Similar topics

6
by: praba kar | last post by:
Dear All, I am new to Python. I want to know how to work with ternary operator in Python. I cannot find any ternary operator in Python. So Kindly clear my doubt regarding this ...
4
by: Bob Gregory | last post by:
Hi all, I don't actually have a mac with which to test this, but I'm informed by a colleague that one of my scripts has failed in IE on the Mac; endless twiddling seems to point to the ternary...
6
by: glongword | last post by:
As the assert macro should evaluate to a void expression, it should not have an 'if statement' in its definition. Does this necessitate the existence of a ternary conditional operator? Is there a...
6
by: Robert Zurer | last post by:
In his paper on Coding Standard found on http://www.idesign.net/idesign/DesktopDefault.aspx Juval Lowy discourages the use of the ternary conditional operator with no specific reason given. ...
48
by: Daniel Crespo | last post by:
Hi! I would like to know how can I do the PHP ternary operator/statement (... ? ... : ...) in Python... I want to something like: a = {'Huge': (quantity>90) ? True : False} Any...
15
by: Arthur Dent | last post by:
Hi all, im just curious if anyone knows..... With .NET 2, VB didnt happen to get a true ternary operator, did it? Stuck away in a corner somewhere? By ternary, i mean something like C's a?b:c...
5
by: PerlPhi | last post by:
hi,,, while ago i was wondering why do some programmers rarely uses the ternary operator. wherein it is less typing indeed. i believe in the classic virtue of Perl which is laziness. well let me show...
4
by: raiderdav | last post by:
I understand how the ternary operator (question mark - ?) works in an if/else setting, but what does it mean when used as a type? For instance, I'm trying to add a get/set in some existing code,...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
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: 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
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.