Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

wrldwzrd89

macrumors G5
Original poster
Jun 6, 2003
12,110
77
Solon, OH
Code:
def makeApplication():
    global app
    app = Application.Application()
    
def getApplication():
    global app
    return app

if __name__ == "__main__":
    global app
    makeApplication()
    del makeApplication
    # Start GUI
    app.mainloop()

When I try to use the above code, the program runs just fine, until something outside this module calls getApplication() - then it gives me an error message:
Code:
Exception in Tkinter callback
Traceback (most recent call last):
(lots of stuff removed for brevity)
   return app
NameError: global name 'app' is not defined

I cannot, for the life of me, figure out why Python's complaining.
 
Where is the global declaration of app? That is, app = ... unindented?

-Lee
There isn't one, because if I create a global one, every time this module gets imported in order to fetch the app variable, a new app gets created - which I don't want.
 
Don't you just want something like this:

Code:
# appmodule.py
from applicationmodule import Application # wherever Application lives...

app = Application.Application()

# if you are executing this module, then run the mainloop
if __name__ == "__main__":
    app.mainloop()
Code:
# anothermodule.py

# Application.Application() is called only once
# however many times app is imported
import appmodule 

# if this module is being run, call mainloop
if __name__ == "__main__":
    appmodule.app.mainloop()

global is used for scope resolution in Python (the rules have changed slightly from 2.x to 3.x and, disclaimer, I haven't used 3.x, YMMV)

if you really want a function, you could do this:
Code:
# appmodule.py

def makeApplication():
    global app
    app = Application.Application()
which will put app into the appmodule namespace after you call makeApplication()
Code:
# anothermodule.py

import appmodule 

try:
    print appmodule.app # appmodule.app doesn't exist
except AttributeError:
    print "AttributeError raised"
    pass

appmodule.makeApplication() # call Application.Application()
appmodule.app.mainloop()  # appmodule.app is now available
and if you want, you can start deleting the module function, but I get the feeling the first option is simplest ...
btw, are you trying to work around a Singleton?
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.