是否存在“内置”方式将变量从另一个模块导入python中的字典,而不是解析模块并手动创建字典?我正在寻找类似的东西:
from myVars import*
d = globals()
但是,以上方法放置了所有变量(来自本地模块和导入的模块),并且还包括一些系统变量,例如_ file _,_ main _等。我不想在字典中。
鉴于 myVars.py 具有以下内容:
myvar1 = "Hello "
myvar2 = "world"
myvar3 = myvar1 + myvar2
当我运行 script.py 时,我只希望将那些变量放入字典中:
from myVars import*
d = someMagicalVariableExtractionFuntion()
print(d)
会给我这个:
{'myvar1': 'Hello ','myvar2': 'world','myvar3': 'Hello world'}
答案 0 :(得分:3)
为什么不使用vars
?
>>> import pprint
>>> import math
>>> pprint.pprint(vars(math))
{'__doc__': 'This module is always available. It provides access to the\nmathematical functions defined by the C standard.',
'__file__': '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/math.so',
'__name__': 'math',
'__package__': None,
'acos': <built-in function acos>,
... <snip> ...
'sinh': <built-in function sinh>,
'sqrt': <built-in function sqrt>,
'tan': <built-in function tan>,
'tanh': <built-in function tanh>,
'trunc': <built-in function trunc>}
如果要过滤掉一些特殊值,则有一些选项。
如果同时控制两个控件,则可以向从中导入控件__all__
的模块中添加一个import *
。
如果要摆脱魔术值,可以枚举它们,或按模式将其删除:
excluded = set(['worst_value', '_bobs_my_uncle', 'xxx_secret_xxx'])
bad = lambda k: k in excluded or k.startswith('__')
d = {k: v for k, v in something.items() if not bad(k)}