Как получить все локальные переменные другого модуля?
Я получаю модуль в качестве параметра, и я хотел бы получить все его локальные переменные (ничего, что не относится к XXX или функции или классу).
Как это можно сделать?
Я пытался:
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('__')]
но это поднимает:
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__'
2 ответа
Решение
Вы можете получить доступ ко всем локальным переменным с помощью dir()
, Это возвращает список строк, где каждая строка является именем атрибута. Это возвращает все переменные, а также методы. Если вы ищете только переменные экземпляра, к ним можно получить доступ через __dict__
например:
>>> 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']
dir()
возвращает список строк. использование setting.startswith()
непосредственно.