Ternary operator alternative in Ptyhon
jeremie fouche
jfouche at voila.fr
Wed Jun 18 13:37:37 EDT 2008
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
More information about the Python-list
mailing list