Module function can't see globals after import.

R

Ron_Adam

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
 
C

Christos TZOTZIOY Georgiou

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?

No, but if you insist on working with globals for some reason of your
own, in the module you can:

import __main__

and access the main modules globals (eg 'x') as:

__main__.x
 
R

Ron_Adam

No, but if you insist on working with globals for some reason of your
own, in the module you can:

Actually I avoid them where ever and when ever possible. ;)

This is more of an attempt to help find and prevent problems of that
sort. I've started to put together a took kit package of sorts for
finding and preventing problems. It needs to look at the name spaces
to work correctly.
import __main__

and access the main modules globals (eg 'x') as:

__main__.x

Thanks, 'That worked fine.! :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top