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. 7 1681
On Wednesday 18 June 2008, kretik wrote:
if params.has_key( "mykey"):
self.SomeField = params["mykey"]
else:
self.SomeField = None
self.SomeField = parms.get('myke y', None)
This looks like what you want and it is also simpler because you don't deal
with checking if the key exists.
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
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
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
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
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
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.
This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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
__________________________________
Yahoo! Messenger
|
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 operator as culprit.
I asked him to check that javascript:alert(true?"Yes":"No"); gave an
alert when pasted into the address bar and he's reported that it does
not.
javascript:alert("someString"); works quite happily.
|
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 way
assert.h can be implemented without using it? Are these decisions
related in anyway?
| |
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.
I can understand that complicated code would be much less readable using nested
operators, but aside from that is there another reason? -- something going on
under the hood perhaps which make it inadvisable to use?
| |
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 suggestions?
|
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 syntax.
IIf works in most cases, but in some instances you want to use expressions
which may fail if they are evaluated when they arent supposed to be, and it
would be nice to have a concise way of writing this instead of using a whole
If-Then-Else...
|
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 you something first before i go to my delimma.
codes as follows using Mrs. If Else:
#!perl/bin/perl
use strict;
print "Are you sure you want to quit ('yes' or any key for 'no'): ";
chomp($_ = <STDIN>);
|
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, but
the return type doesn't match:
Rectangle? m_textArea = null;
public Rectangle TextArea {
set { m_textArea = value; }
get { return m_textArea; }
|
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,...
|
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...
| |
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,...
|
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...
|
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...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
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...
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
| |
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...
| |