[Python-Dev] Switch statement

Guido van Rossum guido at python.org
Fri Jun 23 22:47:18 CEST 2006

On 6/23/06, Jim Jewett <jimjjewett at gmail.com> wrote:
> In http://mail.python.org/pipermail/python-dev/2006-June/066399.html, PJE wrote:
> >> Python prefers to evaluate expressions in the order that they
> >> appear in source code, ... "first-time use" preserves that
> >> property; "function definition time" does not.
> Guido wrote:
> > But first-time has the very big disadvantage IMO that there's no
> > safeguard to warn you that the value is different on a subsequent
> > execution -- you just get the old value without warning.
> That is true either way, and is already true with computed default
> arguments.  The only difference is that your mental model has even
> longer to become inconsistent.  (The time between definition and first
> use.)
> First time use also lets you use a constant (such as a dotted name
> from another module) that may not yet be defined when the function is
> defined, but will be defined before the function is used.

I should probably just pronounce on this; I'm not going to change my
mind, so def-time-freeze it is (if we do this at all). Ditto for
static inside a function (if we do that at all). Static and switch
outside a function are still somewhat open; I'm currently leaning
towards making static expressions outside a function illegal and limit
switches outside a function to compile-time-constant expressions.

Here are a few examples showing my objections against first-use.

def foo(c):
  def bar(x):
    switch x:
    case c: print 42
    else: print 0
  return bar

p = foo(1)
p(1)  # prints 42
q = foo(2)
q(2)  # does this print 42 or 0?

I think q(2) should print 42; otherwise it's not clear what object
should be used to hold the frozen switch dict; it can't be the code
object since code objects need to be immutable and cannot have any
variable state.

But then the def time enters into it anyway...

Another example is this:

def foo(c, x):
  switch x:
  case c: print 42
  else: print 0

Should this be allowed? The first-use rule has no strong motivation to
forbid it, since *knowing* the first-rule it's reasonable to expect
that *any* case expression will just be evalluated in the local scope
at the first use of the switch. But it's just begging for confusion if
the reader isn't clued in to the first-use rule. The def-time rule
simply forbids this; any switch you're likely to write with the
def-time rule is almost certain to use only global and imported
variables that are constants in the user's mind.

With the def-time rule, you'd have to work a lot harder to construct
an example that works differently than the casual reader would expect.

--Guido van Rossum (home page: http://www.python.org/~guido/)

More information about the Python-Dev mailing list