Most compact "X if X else Y" idiom
Aaron "Castironpi" Brady
castironpi at gmail.com
Sun Oct 12 01:25:56 EDT 2008
On Oct 12, 12:01 am, jbperez... at yahoo.com wrote:
> I find myself having to do the following:
>
> x = (some complex expression)
> y = x if x else "blah"
>
> and I was wondering if there is any built-in idiom that
> can remove the need to put (some complex expression)
> in the temporary variable x.
>
> e.g. something like the below:
>
> y= foobar ((some complex expression), "blah")
>
> I realized foobar() can be easily coded as:
> def foobar(a,b):
> if a: return a
> else: return b
>
> But I was wondering if there was a built-in function or syntax
> that already does this.
You could take your chances on 'or', as follows:
>>> (6+ (3<< 1) ) or 'blah'
12
>>> (6- (3<< 1) ) or 'blah'
'blah'
You don't need to use the ternary statement:
y = (some complex expression)
if not y:
y = "blah"
If you find yourself using it a lot, why not add it to your site's
utilities modules? Take your time, and if you find numerous uses,
present them and make the case Python should have a built-in to do it,
something like 'ditto' marks:
(6- (3<< 1) ) if ditto else 'blah'
More information about the Python-list
mailing list