Short if

David Bolen db3l at fitlinxx.com
Wed Jul 7 11:05:09 EDT 2004


Steve Holden <sholden at holdenweb.com> writes:

> Vincent Wehren wrote:
(...)
> > class Klass:
> >   def __init__(self, a, b, foo=None, bar=None):
> >       self.a = a
> >       self.b = b
> >       self.foo = (foo, someDefaultMutable)[foo is None]
> >       self.bar = (bar, someOtherDefaultMutable)[bar is None]
(...)
> I should have thought that this is about the same as
> 
> 	self.foo = foo or someDefaultMutable
> 	self.bar = 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