the_drow
the_drow

Reputation: 19191

How to retrieve all local variables of another module?

I am receiving a module as a parameter and I would like to retrieve all of it's local variables (nothing that relates to XXX or a function or a class).
How can that be done?

I have tried:

def _get_settings(self, module):
        return [setting for setting in dir(module) if not inspect.ismodule(setting) and not inspect.isbuiltin(setting) and not inspect.isfunction(setting) and not setting.__NAME__.startswith('__')]

but it raises:

Traceback (most recent call last):
  File "/home/omer/Aptana Studio 3/plugins/org.python.pydev.debug_1.6.5.2011012519/pysrc/pydevd.py", line 1133, in <module>
    debugger.run(setup['file'], None, None)
  File "/home/omer/Aptana Studio 3/plugins/org.python.pydev.debug_1.6.5.2011012519/pysrc/pydevd.py", line 918, in run
    execfile(file, globals, locals) #execute the script
  File "/root/Aptana Studio 3 Workspace/website/website/manage.py", line 11, in <module>
    import settings
  File "/root/Aptana Studio 3 Workspace/website/website/settings.py", line 7, in <module>
    settings_loader = Loader(localsettings)
  File "/root/Aptana Studio 3 Workspace/website/website/envconf/loader.py", line 6, in __init__
    self.load(environment)
  File "/root/Aptana Studio 3 Workspace/website/website/envconf/loader.py", line 9, in load
    for setting in self._get_settings(module):
  File "/root/Aptana Studio 3 Workspace/website/website/envconf/loader.py", line 16, in _get_settings
    return [setting for setting in dir(module) if not inspect.ismodule(setting) and not inspect.isbuiltin(setting) and not inspect.isfunction(setting) and not setting.__NAME__.startswith('__')]
AttributeError: 'str' object has no attribute '__NAME__'

Upvotes: 0

Views: 530

Answers (2)

Bryan Ward
Bryan Ward

Reputation: 6703

You can access all of the local variables with dir(). This returns a list of strings, where each string is the name of the attribute. This returns all of the variables as well as the methods. If you are looking specifically for just the instance variables, these can be accessed through __dict__ for example:

>>> class Foo(object):
...     def __init__(self, a, b, c):
>>>
>>> f = Foo(1,2,3)
>>> f.__dict__
{'a': 1, 'c': 3, 'b': 2}
>>> dir(f)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'a', 'b', 'c']

Upvotes: 2

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799200

dir() returns a list of strings. Use setting.startswith() directly.

Upvotes: 2

Related Questions