globals函数
globals可以将当前模块中的所有变量、函数、类变成一个字典,然后可以通过名称获取对应的对象。
scope = globals()["AdminScope"]()
获取当前文件的绝对路径
python2:
print((lambda: 0).func_code.co_filename)
python3:
print((lambda: 0).__code__.co_filename)
The function attributes named func_X have been renamed to use the "__X__" form, freeing up these names in the function attribute namespace for user-defined attributes. To wit, func_closure, func_code, func_defaults, func_dict, func_doc, func_globals, func_name were renamed to __closure__, __code__, __defaults__, __dict__, __doc__, __globals__, __name__, respectively.
通过字符串找到类中的静态字段(类属性)
"""
config/setting.py:
class Foo(object):
DEBUG = True
TEST = False
"""
path = "config.setting.Foo"
import importlib
p, c = path.rsplit(".", 1)
m = importlib.import_module(p)
cls = getattr(m, c)
for key in dir(cls):
if key.isupper():
print(key, getattr(cls, key))