Accessing one's main script's global from imported libraries

John La Rooy nospampls.jlr at doctor.com
Thu Feb 27 17:24:23 EST 2003


marshall wrote:
> czrpb <nanotech at europa.com> wrote in message news:<mailman.1046111768.26279.python-list at python.org>...
> 
>>All:
>>
>>Say I have spam.py with the global taste.
>>Say in spam.py I import eggs.
>>Say I want eggs to access spam.py's taste global.
>>
>>How might I do this?
>>
>>thanks!! Quentin
>>
> 
> 
> As you will no doubt read, you are not _supposed_ to do this.  You are
> _supposed_ to be passing parameters from the objects or functions in
> spam.py to the objects or functions in eggs.py.  However, I have
> believe the best practice to acheive what you want is to have a
> separate file (e.g. spamglobals.py) and have all other files import
> that.  I could very well be wrong about that but that is what works
> for me (newbie disclaimer).
> 
> I think the more general question is: "What is the best way to split a
> large program up into several modules and still let them all have
> access to application global data?"
> 
> What I have been doing is creating an Application instance which has
> all of the global data (like maxscreensize, datapath, etc.) as
> attributes.  Then I pass this App instance as a parameter to every
> other object that the application creates.  If there is a better way I
> would sure like to hear about it.
> 
> Marshall

Would something like this work for you?


===globaldemo.py===
#!/usr/local/bin/python
import mod1
import mod2
mod1.setx()
mod2.printx()

===mod1.py===
import globals
def setx():
     globals.x=10

===mod2.py===
import globals
def printx():
     print globals.x

===globals.py===
# nothing needs to be in here

John





More information about the Python-list mailing list