peter at engcorp.com
Wed Jul 7 17:12:29 CEST 2004
David Bolen wrote:
> Steve Holden <sholden at holdenweb.com> writes:
>>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.
That is true of course, but keep in mind also that the most common
use of such patterns is actually to initialize self.foo to an
*empty* mutable of the appropriate type. In that case (and that
case alone), it is generally equivalent at least in outcome, as
if the user passes in an empty (say, list), the above code will
use the "someDefaultMutable" empty list instead, but the result
is still what was desired in most cases.
But it is good to know the distinctions, and the fact that there
are such distinctions still means that good ol' "if/else" is still
the safest way to go...
More information about the Python-list