Help on scope/namespace

Bengt Richter bokr at oz.net
Mon Feb 3 00:14:26 EST 2003


On Sun, 02 Feb 2003 03:48:12 GMT, "Byron Morgan" <lazypointer at yahoo.com> wrote:

>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.
>
>I have nearly 100 functions that I'd like to import, rather than maintaining
>them in the main script. I tried putting them into their own file, but they
>couldn't see the objects  (dictionaries & lists) that were loaded from the
>first file. So I tried putting them in the same file, but this didn't work
>either. So I made a class with all the functions inside, still no go.
>
>It's not that I haven't read the documentation on namespaces and scoping: it
>just seems like doubletalk to me.
>
>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 ?
>
Maybe what you want to do is execfile in the main script instead of import.
That has an effect sort of like a dynamic #include. IOW, the function definition
code (remember def is an executable statement that builds a function) is
executed in the main script scope (unless you use non-default 2nd and 3rd args
to specify something else), and the effect is as if the source defs were right there.

The thing about this is that it does not create a separate module instance that
can be imported as a shared module instance. An execfile could be done within a
shared module though, and the effect would be visible to all sharers of that module.

Something to keep in mind: Any cluttered namespace carries risk of confusion
and name clashes. IOW, don't do that casually. Execfile will pull all those function
names into the namespace you specify, by default or otherwise, e.g.,

====< t_execf.py >=========================
g_var = 123

def foo(x):
    global g_var
    g_var = x
===========================================

 [21:19] C:\pywk\clp>python
 Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32
 Type "help", "copyright", "credits" or "license" for more information.
 >>> dir()
 ['__builtins__', '__doc__', '__name__']
 >>> execfile('t_execf.py')
 >>> dir()
 ['__builtins__', '__doc__', '__name__', 'foo', 'g_var']
 >>> g_var
 123
 >>> foo('new value')
 >>> g_var
 'new value'

Regards,
Bengt Richter




More information about the Python-list mailing list