Need help with Python class idioms

James Henderson james at logicalprogression.net
Thu Jan 22 19:43:40 CET 2004


On Thursday 22 January 2004 6:05 pm, Mel Wilson wrote:
> In article <mailman.613.1074720629.12720.python-list at python.org>,
>
> James Henderson <james at logicalprogression.net> wrote:
> >On Wednesday 21 January 2004 9:01 pm, Jonathan Daugherty wrote:
> >> # P.S. Since you're asking about idiom, it would be more Pythonic to
> >> write: #
> >> #     if self.mandatoryVar1 is None:
> >> #
> >> # using the identity test "is" rather than equality test "==", since
> >> there is # only one None.
> >>
> >> I'd write
> >>
> >>   if not self.mandatoryVar1:
> >>
> >> but the first method works, too.
> >
> >Are you sure an empty sequence or zero aren't valid values?  J.
>
>    It can get weird if you have to allow your caller to
> optionally specify the value None:
>
>
>     class _MissingParam:
>         "An object that no-one else will have a valid use for."
> ...
>     def a_func (opt1=_MissingParam):
>         if opt1 is _MissingParam:
>             opt1 = default_calculation ()       # for instance
> ...
>
>
>         Regards.        Mel.

In the original example (not by me) it was None that was being used as the 
marker that the value had not been set - that's all.

The topic was Python idiom and None is the most often used marker that a value 
has not been passed explicitly and the default value should be used.  (Of 
course, if the default value is immutable it can be used directly.)  See:

http://www.python.org/doc/current/ref/function.html

You're talking about the case where None may be passed explicitly and should 
not trigger the default.  An even terser solution to this than yours is to 
use an empty list, though any mutable type will do.  You see this all over 
the Zope code:

_marker = []

J.
-- 
James Henderson, Logical Progression Ltd.
http://www.logicalprogression.net/
http://sourceforge.net/projects/mailmanager/





More information about the Python-list mailing list