Problem with Lexical Scope

Bengt Richter bokr at oz.net
Mon Dec 12 06:37:49 EST 2005


On Mon, 12 Dec 2005 08:26:59 +0000, Steve Holden <steve at holdenweb.com> wrote:
[...]
>
>The scoping rules do work when you obey them:
>
>  >>> def f1(a, b):
>  ...   s = a+b
>  ...   def _(x):
>  ...     return s+x
>  ...   return _
>  ...
>  >>> func = f1(12, 13)
>  >>> func(10)
>35
>  >>>
>
>Here the nested lexical scopes rule isn't that helpful given the 
>overriding nature of assignment within an inner scope. Using global will 
>simply put the status variable at *module* scope, which also isn't what 
>you want.
>
Is external rebindability being considered at all ?

what if it were a new builtin that could do it in C, e.g. rebind(targetname, expr)
where target could be in any enclosing scope (including globals(),
but not extending to __builtins__) and it would be a NameError if target
didn't exist. Thus this would be possible (untested and currently impossible ;-)

    def mkbumper(initval, incr):
        def _():
            rebind('initval', initval+incr) # vs initval := initval+incr
            return initval
        return _

    bump3 = mkbumper(8, 3)
    bump3() => 11
    bump3() => 14

I wonder if a function would fly better than a punctuation tweak on
bare name assignment ;-)

Regards,
Bengt Richter



More information about the Python-list mailing list