Creating a local variable scope.

Terry Reedy tjreedy at udel.edu
Fri Sep 11 16:29:26 EDT 2009


Johan Grönqvist wrote:
> 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.

delete spam, eggs

rather effectively says that the reader can also forget the bindings.
Execution time is minimal since no object is gc'ed.

This works with function locals also:

 >>> def f():
	i=1; del i; print (i)

	
 >>> f()
Traceback (most recent call last):
   File "<pyshell#6>", line 1, in <module>
     f()
   File "<pyshell#5>", line 2, in f
     i=1; del i; print (i)
UnboundLocalError: local variable 'i' referenced before assignment

However, since probably a majority of non-function bindings are rather 
local, I do not see that this really improved readability.

Within a module intended to be imported, using _spam, _eggs would signal 
that they are only inted for local use. Delete if you want to enforce that.

> The language reference at
> <http://docs.python.org/reference/executionmodel.html> 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.

Not exactly. In 3.0, comprehensions define a new scope by virtue of 
being implicit function bodies.

> 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 consider that simplicity of Python scoping to be a major feature; it 
is one of the reasons I use it.

tjr





More information about the Python-list mailing list