Module function can't see globals after import.

Ron_Adam radam2 at tampabay.rr.com
Mon Mar 28 12:19:42 EST 2005


Using this example:

[in mymodule]

def whatisx():
    try:
        print 'x is',x
    except:
    	print 'There is no x'


[in mymain]

from mymodule import printx
x = 10
whatisx()

prints -> There is no x


Is there a way to tell the imported function printx to use mymain's
globals instead of it's own copy without passing it as an argument?

I'm experimenting with a function that limits both the reading and
writing of globals and builtins to only specific names.  But after
it's imported it has it's own globals so it only works if it's copied
to the current module.


def howareyou():
    allow_globals( rw_globals='y', r_globals='x', builtins='int')
    global y         # This is still needed.  
    # ... lots more code.
    y = int(x*y)
    return 'I am fine.'

x = 5
y = 10
print howareyou()

    
This function has read/write access to y, can only read x, and has
only read access to int().  It will generate an error if an attempt is
made to use anything other than what is specified.  

Using:
   allow_globals()   # No globals, and all builtins.
   allow_globals(builtins=None)   # No globals, and no builtins.

Still have a few minor issues to work out.  Like getting it to work
correctly after it's imported. :/

Ron_Adam






















More information about the Python-list mailing list