accessing module global vars by name

M

Martin Drautzburg

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
 
S

Steven Bethard

Martin said:
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]
Traceback (most recent call last):
Traceback (most recent call last):
File said:
>>> 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.
 
P

Peter Hansen

Martin said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,012
Latest member
RoxanneDzm

Latest Threads

Top