[Python-Dev] once [was: Simple Switch statementZ]

Jim Jewett jimjjewett at gmail.com
Wed Jun 28 18:12:31 CEST 2006

On 6/25/06, Ka-Ping Yee <python-dev at zesty.ca> wrote:

>     def f(x):
>         def g(y):
>             return y + once x
>         return g

> Does "once" mean not really once here, but "once for each new function
> object that's created for g"?

Until today, it hadn't really occurred to me that once could mean once
per module load rather than once per defining scope.  I suppose that
is reasonable if the values really are constant, but most of the
concerns are about what to do when this assumption is violated.  It
does add a bit of funny flow-control, though.

    def f():
        def g():
            def h():
                once x # or switch

Normally, there wouldn't be any need to even look inside g (let alone
h) at module load time, because the definition of f was run, but the
definitions of g and h were not.  With module-level once, x is
implicitly a module-level variable despite the nesting.


> He specifically wants the latter semantics because it solves the
> problem of binding the value of a loop control variable in an outer
> scope:

Not really.  To solve the loop control problem (where the "constant"
is certainly not a run-time constant), a once variable also has to be
eagerly evaluated.  (function definition time?)

Nick suggested using once to delay computation of expensive defaults.
This means that even if every generated function has its own once
variable, none of those variables would be bound to any specific value
until they are called -- by which time the loop variable may well be


More information about the Python-Dev mailing list