Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > accessing module global vars by name

Reply
Thread Tools

accessing module global vars by name

 
 
Martin Drautzburg
Guest
Posts: n/a
 
      12-20-2004
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
 
Reply With Quote
 
 
 
 
Steven Bethard
Guest
Posts: n/a
 
      12-20-2004
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.
 
Reply With Quote
 
 
 
 
Peter Hansen
Guest
Posts: n/a
 
      12-20-2004
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
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Use self.vars in class.method(parameters, self.vars) caccolangrifata Python 18 07-22-2011 10:22 PM
How do I declare global vars or class vars in Python ? Linuxguy123 Python 7 02-20-2009 06:45 PM
app vars and cache vars Jon ASP .Net 3 12-14-2004 08:52 PM
Trouble accessing global vars Fernando Rodríguez Python 6 09-06-2004 07:27 AM
How to access my module global vars ? Kepes Krisztian Python 0 11-25-2003 05:47 PM



Advertisments