[Python-3000] else Versus or (Was: Re: default argument surprises)

Eric Astor eastor1 at swarthmore.edu
Wed Aug 27 07:15:48 CEST 2008


Chris Monson wrote:
>     Now thinking as a language designer, C# has a ?? operator where A??B
>     is shorthand for (B if A is None else A) except you only have to
>     write A once and A is only evaluated once. A Pythonesque version of
>     this would be just "else":
> 
>        def foo(arg=None, arg2=None):
>           arg = arg else bar
>           arg2 = arg2 else list()
>          
>     And I think that metaphor is easy to read. Chains of else operators
>     can be useful:
> 
>        x = f() else g() else h() else 0
> 
> 
> Not a bad idea.  Looks like the time machine is at work again:
> 
> x = f() or g() or h() or 0

True, but 'else' can be a more specific operator, so that

>>> arg = arg else bar

is equivalent to:

>>> if arg is None: arg = bar,

where

>>> arg = arg or bar

is instead equivalent to:

>>> if not arg: arg = b

This has the advantage of being more linguistically clear and/or
unambiguous. No nasty surprises when someone calls foo(0, []); using or,
you'd get default argument treatment when you might need the values as
specified. This is basically the reasoning used for introducing

>>> arg = b if a else c

where we had a hack before that failed in certain corner cases

>>> arg = a and b or c

It's a little more nuanced here, I admit, but it doesn't seem like it
would kill anything too badly. If we weren't freezing, it'd be something
to toss around and explore - as it stands, maybe this should get filed
as an idea for the future.

- Eric Astor


More information about the Python-3000 mailing list