Creating a local variable scope.
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Fri Sep 11 21:29:55 EDT 2009
On Fri, 11 Sep 2009 19:36:14 +0200, 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.
...
> 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.
Personally, I don't think your use-case is the least bit convincing, and
I think that introducing a new scope would hurt readability and clarity
rather than help it, but if you really want this, there are a couple of
approaches:
(1) Use comments to give your intention.
spam = 'abc' # Used only in definition of ham.
eggs = 'def' # Likewise.
ham = (a[eggs], b[spam])
(2) Delete the local names afterwards.
spam = 'abc'
eggs = 'def'
ham = (a[eggs], b[spam])
del spam, eggs
(3) Create an inner function, then call that.
def outer(*args):
a = parrot()
b = spanish_inquistion()
def inner():
spam = 'abc'
eggs = 'def'
return a[eggs], b[spam]
ham = inner()
return do_something_with(ham)
(4) Create a "do nothing" context manager allowing you to visually indent
the block, but otherwise have no effect:
class do_nothing:
def __enter__(self):
pass
def __exit__(self, type, value, traceback):
pass
ham = ()
with do_nothing() as imaginary_local_scope:
spam = 'abc'
eggs = 'def'
ham = a[eggs], b[spam]
del spam, eggs, imaginary_local_scope
I think the fourth is an abomination and I only mention it for completion.
My personal opinion is that if you really need a local scope inside a
function, the function is doing too much and should be split up.
--
Steven
More information about the Python-list
mailing list