Ternary operator alternative in Ptyhon

Robert Lehmann stargaming at gmail.com
Wed Jun 18 08:27:33 CEST 2008


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



More information about the Python-list mailing list