sort of a beginner question about globals
Steven Bethard
steven.bethard at gmail.com
Wed Apr 13 23:04:58 EDT 2005
fred.dixon wrote:
> #global1.py
> import global2
> import global3
> import sys
>
> constant = 'dumb'
> option = sys.argv[1:]
> pass
> #global2.func1()
> a=global2.class1()
> a.func1()
> print newvar
>
> #global2.py
> import __main__
> pass
> class class1:
> def func1(self):
> __main__.newvar = "string"
> pass
The other ways of getting this behavior would be to write global2.py as:
class class1:
def func1(self):
global newvar
newvar = "string"
or
class class1:
def func1(self):
globals()["newvar"] = "string"
or
class class1:
def func1(self):
__import__(__name__).newvar = "string"
I don't know which of these is really preferred. Generally if I see
myself writing code like this, I figure I probably need to refactor things.
STeVe
P.S. Why are you writing all those 'pass' statements? They're not
necessary in any of the locations you've placed them.
More information about the Python-list
mailing list