Creating a local variable scope.

Patrick Sabin patrick.just4fun at
Fri Sep 11 20:37:49 CEST 2009

Johan Grönqvist schrieb:
> Hi All,
> I find several places in my code where I would like to have a variable
> scope that is smaller than the enclosing function/class/module definition.
> One representative example would look like:
> ----------
> spam = { ... }
> eggs = { ... }
> ham = (a[eggs], b[spam])
> ----------
> The essence is that for readability, I want spam and eggs in separate
> definitions, but for clarity, I would like to express the fact that they
> are "local to the definition of ham", i.e., they are not used outside of
>  the definition of ham.
> The language reference at
> <> says that "The
> following are blocks: a module, a function body, and a class
> definition." (all other cases seem to refer to dynamic execution using
> eval() or similar). Python 3 and 2.6 seem to have identical scope rules.
> 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.
> Are there suggestions or conventions to maximize readability for these
> cases in python? (Execution time is not important in the cases I
> currently consider.)
> Regards
> Johan

I think it is not possible to realize something like braces in C or 
let-bindings in python. But here are some Ideas to work around this problem:

1) If you define all this in the global namespace you could remove your 
temporary variables afterwards, e.g.

spam = 1
ham = (spam,)
del globals()['spam']

This only works for the global namespace and not for the local! I 
wouldn't recommend it.

2) create a method, which initializes ham

def make_ham():
	spam = {...}
	egg = {...}
	return (egg, spam)

ham = make_ham()

This makes it easier to reuse ham in other situations and wouldn't 
expose spam or egg.

3) Make a class for your ham data structure

If ham is so complex that you have to split it up, it may makes sense to 
create a class for it. Of course this would need refactoring of the 
code, but it's more readable and extensible than packing your data in 
tuples, lists or dictionaries.

- Patrick

More information about the Python-list mailing list