By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,516 Members | 1,168 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,516 IT Pros & Developers. It's quick & easy.

accessing module global vars by name

P: n/a
Withing a module I can assign a value to a global var by assigning to
it in the outermost scope. Fine.

But how can I do this if the attribute name itself is kept in a
variable. Once the module is loaded I can access the module's
namespace no problem, but inside the module the dictionary is not yet
present right ?

IOW how can I write something like

# xxx.py

for varName in ("foo", "bar"):
magic.varName = 1

so I can later refer to them as

# yyy.py
import xxx
x = xxx.foo
y = xxx.bar
Jul 18 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
Martin Drautzburg wrote:
IOW how can I write something like

# xxx.py

for varName in ("foo", "bar"):
magic.varName = 1


I think you want to use the dict returned by globals(). Modifying this
dict can add/remove names from the global scope.[1]
foo Traceback (most recent call last):
File "<interactive input>", line 1, in ?
NameError: name 'foo' is not defined bar Traceback (most recent call last):
File "<interactive input>", line 1, in ?
NameError: name 'bar' is not defined for var_name in ['foo', 'bar']: .... globals()[var_name] = True
.... foo True bar True del globals()['foo']
foo

Traceback (most recent call last):
File "<interactive input>", line 1, in ?
NameError: name 'foo' is not defined

Steve

[1] As an aside, be careful not to try the same thing with locals().
locals() returns a dict that won't modify names in the local scope.
Jul 18 '05 #2

P: n/a
Martin Drautzburg wrote:
Withing a module I can assign a value to a global var by assigning to
it in the outermost scope. Fine.

But how can I do this if the attribute name itself is kept in a
variable. Once the module is loaded I can access the module's
namespace no problem, but inside the module the dictionary is not yet
present right ?


Look into the builtin function globals()...

-Peter
Jul 18 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.