A way to get a handle to the current running module in Python:
import sys
module = sys.modules[name]
it really only works if you are doing the whole sys.modules litany in the very module you want to get a handle to.
So, getattr (sys.modules [ name ], func_name) is to find the meaning of the name of the current file func_name object (the class object or function object).
Sometimes we need information about a file (classes, functions and variables) saved to a file, we can not directly save function object, but will be converted to fn.__name__
, the question is, when we want to re-read the configuration file in the form of these classes when the function, how to convert these strings corresponding function objects?
# test.py
import sys
def fn():
print('hello world')
func_name = fn.__name__ ####这个可能是从url中获取的字符串
fn_obj = getattr(sys.modules[__name__], func_name)
# 根据函数名(func_name),获得函数对象
fn_obj()
# hello world
print(sys.modules[__name__])
# <module '__main__' from '**/test.py'>