2 questions about scope

Alex Martelli aleaxit at yahoo.com
Mon Oct 25 16:53:39 EDT 2004


Andrew Dalke <adalke at mindspring.com> wrote:
   ...
> but you really shouldn't.  Or use a function scope,
> 
>    i = "something"
>    def scope():
>      for i in range(100):
>        ...
>    scope()
> 
> I mostly use the last when I want some non-trivial
> initialization in my module and don't want the various
> variables hanging around in the process space.  I'll
> also follow it up with a "del scope" so that no one
> can reference the initialization code.

Execution in function scope is also generally quite a bit faster than
execution at module scope or in class scope.  Any nontrivial code in
module scope is best scooped up into a function, which is then executed
and removed.  I'd suggest naming the function '_init' or something like
that -- with a leading underscore to indicate to the reader of the
source that it's a private implementation detail (not _needed_, since
you're gonna delete it after running it once, but helpful to the reader
at no cost to the code's author).


Alex



More information about the Python-list mailing list