Help on scope/namespace

Mike Meyer mwm at mired.org
Sun Feb 2 17:57:10 CET 2003


"Byron Morgan" <lazypointer at yahoo.com> writes:

> Well, I've gotten far enough into my first Python project that I would like
> to split up the source. From the start, I built a library of dictionaries,
> which I import at runtime, and this works fine. I discovered that if I
> wanted to change a variable declared outsid a fuction, I had to declare it
> as 'global' with the function.
[...]
> Is there some way I can import functions from a file, and have them behave
> just as though they are contained in the main script ?

Since you mentioned the "global", I suspect that the real problem is
that you've got global data in your main file, and want to access that
from the functions you are putting in the second file.

You can't do that.

Global data is generally considered a bad idea, and you've just found
one of the reasons why. The solution is to figure out which of your
functions can be rewritten to use an argument instead of a global
without breaking them - this should be easy, as you turn:

        def function(arg):
            global globvar
            ...

into
        def function(arg, globvar):
            ...

Any function that does an assignment to a global variable can't be
changed this way. Take all the functions that can be rewritten, move
them - in their new form - to a second file, say tools, and do the
"from tools import *" already suggested here. Don't forget to rewrite
the function invocations as well.

        <mike
-- 
Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.




More information about the Python-list mailing list