Global help

Thomas Wouters thomas at xs4all.net
Mon Jan 17 11:53:43 EST 2000


On Mon, Jan 17, 2000 at 04:18:01PM +0000, Shaun Allen Dishman wrote:

> 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.

Well, if you _really_ need it as a global in y, you can do the following:


-------- x.py --------
import y

def x(filename):
	file = open(filename, 'w')
	y.y()
	
----------------------

-------- y.py --------

y.file = None

def y():
	y.file.write("spam spam spam\n")
----------------------

Or, if you must have the 'from y import *' statement:

-------- x.py --------
from y import *

def x(filename):
	setfile(open(filename, 'w'))
	y()
	
----------------------

-------- y.py --------

file = None

def setfile(newfile):
	global file
	file = newfile

def y():
	file.write("spam spam spam\n")
----------------------

But, in general, the from y import * statement is a Bad Thing. You can
overwrite your own functions/variables/classes, or the builtin ones, and not
notice it for weeks.

Think-from-perl-import-use-without-qw()-ly y'rs,

-- 
Thomas Wouters <thomas at xs4all.net>

Hi! I'm a .signature virus! copy me into your .signature file to help me spread!




More information about the Python-list mailing list