Creating a local variable scope.

Sean DiZazzo half.italian at gmail.com
Sat Sep 19 00:45:45 CEST 2009


On Sep 11, 10:36 am, Johan Grönqvist <johan.gronqv... at gmail.com>
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.
>
> 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.
>
> 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 would do something like this:

>>> class Namespace(object):
...     pass
...
>>> n = Namespace()
>>> n.f = 2
>>> n.g = 4
>>> print f
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'f' is not defined
>>> print n.f
2

~Sean



More information about the Python-list mailing list