Global help

Gordon McMillan gmcm at hypernet.com
Mon Jan 17 12:56:37 EST 2000


Shaun Allen Dishman writes:
> 
> I have something like the following situation:
> 
> ----- x.py -----
> 
> from y import *
> 
> def x(filename):
> 	file = open(filename, 'w')
> 	y()
> 
> ----------------
> 
> ----- y.py -----
> 
> def y():
> 	# must be the same file object as in x.py
> 	file.write('blah blah blah \n')	
> 
> ----------------
> 
> I have fiddled around with the global settings for the file object but
> cannot seem to get things to work.  All I need is to be able to access the
> file object from one module inside of another one, without passing it as a
> parameter.  Is this even possible?  Thanks in advance.

Pass it as a parameter anyway.

But if you really insist, you've got 2 choices: put the file in y's 
globals or put the file in x's globals.

To do the former, don't use "from y import *", just use "import 
y" and then "y.file = ... "

To do the latter, add "import x" to the top of y, and 
"x.file.write(...)".

However, if either one of these is __main__, it won't work; the 
non-__main__ module will have to "import __main__" and use 
"__main__.file..."

So give yourself a break and pass it as a parameter.


- Gordon




More information about the Python-list mailing list