Creating a local variable scope.

Carl Banks pavlovevidence at gmail.com
Fri Sep 11 23:32:03 CEST 2009


On Sep 11, 10:36 am, Johan Grönqvist <johan.gronqv... at gmail.com>
wrote:
> In the other languages I have used I can either use braces (C and
> descendants) or use let-bindings (SML, Haskell etc.) to form local scopes.

I wouldn't mind a let statement but I don't think the language really
suffers for the lack of it.  I expect that "leaky scopes" are a really
minor source of bugs in practice**, especially with well-organized
code that results in small functions.  The main loss is the
organization opportunity.

Having said that, I'll tell you a pretty spiffy way to do it, even
though it can't be regarded as anything other than a cute hack.  I
don't recommend using it in practice.


First define a decorator:

def let(f): return f()


Then, apply this decorator to a nameless function to get a convenient
nested scope:

@let
def _():
    a = 1
    b = 2
    print a,b


But there's more: you can define let bindings in the function
arguments:

@let
def _(a = 1, b = 2):
    print a,b


And, as with LISP, the "let" "statement" can return a result which you
can bind to a local variable:

@let
def result(a = 1, b = 2):
    return a + b

print result


Don't do this in real code, though.  Just live with the limitation, or
define a nested function and call it explicitly without cute decorator
hacks.


Carl Banks


(**) There is one notable common bug that leaky scopes do cause, when
creating closures in a loop.  However, that is an advanced usage.



More information about the Python-list mailing list