Help on scope/namespace

Alex Martelli aleax at aleax.it
Sun Feb 2 20:52:17 CET 2003


Byron Morgan wrote:
   ...
> Depending on the parsing results, globals are modified , so that other
> functions can use them.
> 
> I find that if I load a function from a file, the dictionaries are not
> available.
> 
> It is not practical to pass all 10 dictionaries as parameters  on each
> function call, then pass them back as results.

Just pass in a list of the ten dictionaries (a list which you
only need to prepare once) -- no need to pass them nor it back
as result[s], if as you say you're MODIFYING the dictionaries
(if you're REBINDING global names, that's different, of course).

Python doesn't copy arguments implicitly -- it uses references
to the same objects you pass in (when you want a copy you must
explicitly ask for one).  So, for mutable arguments, modifying
them DOES affect the original value you passed in.  This is
quite fast.

There are many alternatives, but this is the cleanest.

Also, for speed & order, group the code you now have at top level in the
main module into a function, say def main(), and make all the now-global
variables into locals of main -- the only top-level statement apart from
imports and def's would then be a call to main().  Referencing local
variables is a bit faster than referencing global ones, and this
organization is also more orderly.  (In python, it's far from rare
that the simplest and most elegant approach is also quite fast).


Alex





More information about the Python-list mailing list