'Import sys' succeeds in C++ embedded code, but module is not fully visible

greg greg at cosc.canterbury.ac.nz
Tue Feb 10 01:58:08 EST 2009


Ben Sizer wrote:
> Yes, this seems to fix it, thanks. But why? Can some Python guru
> explain why these two dictionaries must be the same? (Or what steps we
> must take if we want them to be separate?)

What's happening is that the import statement is binding
the name 'sys' in the locals, not the globals. You don't
notice this in the top-level code, since both are in scope
there. But inside the function you can only see the top-level
globals plus the function's own locals.

> I had hoped to be able to clear out the locals dictionary
> while leaving useful functions intact in the globals dictionary, but
> it would appear that is not practical.

You can probably do that by using global statements in the
top-level code for the things you want to preserve, e.g.

    global sys
    import sys
    my_local_var = 42

    global f
    def f():
      print "This function is in globals and can see sys.path"
      print sys.path

    def g():
      print "This function is in locals and can't see sys.path"

Now clearing the locals will remove g and my_local_var
while leaving the rest in globals.

The only restriction is that anything you want to refer
to from a function will have to be in the globals. This
includes other functions -- i.e. f() won't be able to
call g() in the example above.

-- 
Greg



More information about the Python-list mailing list