[Python-Dev] Switch statement
Phillip J. Eby
pje at telecommunity.com
Mon Jun 19 14:51:40 CEST 2006
At 12:28 AM 6/19/2006 -0700, Josiah Carlson wrote:
>"Phillip J. Eby" <pje at telecommunity.com> wrote:
> > At 06:56 PM 6/18/2006 -0700, Josiah Carlson wrote:
> > >The non-fast version couldn't actually work if it referenced any names,
> > >given current Python semantics for arbitrary name binding replacements.
> >
> > Actually, one could consider "case" expressions to be computed at function
> > definition time, the way function defaults are. That would solve the
> > problem of symbolic constants, or indeed any sort of expressions.
>
>Using if/elif/else optimization precludes any non-literal constants, so
>we would necessarily have to go with a switch/case for this semantic. It
>seems as though it would work well, and wouldn't be fraught with
>any of the gotchas that catch users like:
> def fcn(..., dflt={}, dflt2=[]):
>...
>
>
> > An alternate possibility would be to have them computed at first use and
> > cached thereafter.
> >
> > Either way would work, and both would allow multiple versions of the same
> > switch statement to be spun off as closures without losing their
> "constant"
> > nature or expressiveness. It's just a question of which one is easier to
> > explain. Python already has both types of one-time initialization:
> > function defaults are computed at definition time, and modules are only
> > loaded once, the first time you import them.
>
>I would go with the former rather than the latter, if only for
>flexibility.
There's no difference in flexibility. In either case, the dictionary
should be kept in a cell in the function's closure, not with the code
object. It would simply be a difference in *when* the values were
computed, and by which code object. To be done at function definition
time, the enclosing code block would have to do it, which would be sort of
weird from a compiler perspective, and there would be an additional problem
with getting the line number tables correct. But that's going to be tricky
no matter which way it's done.
More information about the Python-Dev
mailing list