Short if

David Bolen db3l at
Wed Jul 7 17:05:09 CEST 2004

Steve Holden <sholden at> writes:

> Vincent Wehren wrote:
> > class Klass:
> >   def __init__(self, a, b, foo=None, bar=None):
> >       self.a = a
> >       self.b = b
> > = (foo, someDefaultMutable)[foo is None]
> > = (bar, someOtherDefaultMutable)[bar is None]
> I should have thought that this is about the same as
> = foo or someDefaultMutable
> = bar or someOTherDefaultMutable
> but as you say, tastes vary. I find the latter much more readable, as
> I don't have to mentally convert the Boolean to a zero or one
> subscript value to realise what happens when foo *is* None.

Except that your code will result in using the default mutable if a
user passes in their own mutable that happens to be empty.  That may
still work in some cases, but it's certainly not equivalent code.  In
Vincent's example, None is a true Sentinel value (thus the "is" check)
and isn't just being used as equivalent to any false value.

Of course, this use case is really only needed due to Python's
handling of default variables (constructed once at compile time),
making it unsuitable in many cases when the default variable should be
mutable.  So if there were a way to address that in a backwards
compatible manner, it would also simplify this scenario.

-- David

More information about the Python-list mailing list