I have two files that I am trying to work with. menu.py has the menus that program.py imports.
menu.py:
import cmd,sys
user = 'no one'
class loginMenu(cmd.Cmd):
def postloop(self):
user = 'lilith'
return user
intro="""login menu"""
def do_smtoggle(self,person):
return True
def do_quit(self,person):
sys.exit()
class storeMenu(cmd.Cmd):
intro="""store menu"""
def do_whoami(self,person):
print 'storemenu ' + user
def do_quit(self,person):
quit = True
return quit
program.py:
from menu import *
import cmd,sys
lm = loginMenu()
sm = storeMenu()
while True:
lm.cmdloop()
print user
sm.cmdloop()
I expect that when program.py gets to print user it will print lilith but instead it prints no one. Why is this? postloop() is defined in the docs as a method that executes when cmdloop() is about to return so I thought it would return the value of user as lilith and then lilith would be printed but it just prints no one.
edit: It has been recommended that I not use globals. I am reading this to find out why.
That’s because the assignment to
userhere:is acting on a local instance of the var. To affect the global var
user, you would need to add a:to the top of that function. Though I wouldn’t recommend it, as there are usually better ways to do things than to use globals.
One note about globals and python. While you can’t assign a value to a global var without the
globalkeyword, you can read global (and other non-local) scopes, without it. This allows you to make closures.