Is it explicitly specified?

Paul Boddie paul at boddie.org.uk
Mon Feb 4 00:31:49 CET 2008


On 3 Feb, 16:41, mario <ma... at ruggier.org> wrote:
>
> In one case, the collection attributes a specific meaning to
> attr=None, but the actual default for attr is something else. However,
> if an object explicitly wants to state that his attr=None (that is a
> valid value, and has specific meaning) I would like to use that as
> value, but if no value is supplied for attr by the object, then I
> would like to use the default value from the collection.

I don't know whether I can offer much better advice than others, but I
have noticed that a lot of my own code has moved in the direction of
not having specific default values in function/method signatures. So,
instead of this...

  def f(x=123):
    ...

...I have this:

  def f(x=None):
    if x is None:
      x = 123

Of course, you can shorten this to "x = x or 123", but consider what
might happen if x is given as 0. As for exposing the defaults, it's
always possible to define them elsewhere, something which is very
feasible with classes:

  class X:
    default = 123
    def f(self, x=None):
      if x is None:
        x = self.default # or X.default

The main reason for avoiding preset defaults has been to allow
unspecified values to "cascade" through several levels of functions,
if required, with the default being chosen at the most appropriate
place.

Now, your problem would involve explicitly specified values of None
which would inadvertently cause the default to be used in the above
cases. As others have said, a "sentinel" or special value would
probably be a good replacement for None:

  class NotSetType: pass
  NotSet = NotSetType() # or just use object()

  def f(x=NotSet):
    if x is NotSet:
      x = 123

You could even explicitly pass NotSet to the function, too.

Paul



More information about the Python-list mailing list