accessing module global vars by name

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Martin Drautzburg

    #1

    accessing module global vars by name

    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
  • Steven Bethard

    #2
    Re: accessing module global vars by name

    Martin Drautzburg wrote:[color=blue]
    > IOW how can I write something like
    >
    > # xxx.py
    >
    > for varName in ("foo", "bar"):
    > magic.varName = 1
    >[/color]

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

    Comment

    • Peter Hansen

      #3
      Re: accessing module global vars by name

      Martin Drautzburg wrote:[color=blue]
      > 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 ?[/color]

      Look into the builtin function globals()...

      -Peter

      Comment

      Working...