本文主要是利用闭包来实现一种高级的python函数调用方式:调用包外函数,并且当包外函数调用规则改变时,将会使用最新的函数方法。
通过该方式很容易实现架构风格中的基于规则的架构风格,例如当我们存在一笔消费,正常情况下,满100减5,当发生活动时,需要满100减20,且该规则没有在前期开发中进行实现,那么我们在不进行程序重启的情况下是很难实现规则的改变,因此可以通过本文来实现类似的需求。
一、闭包
在python中闭包的使用情况其实不算特别频繁,但我们很多情况下会使用装饰器来进行开发。如果在装饰器中的函数调用了外层函数的局部变量,那么这个装饰器就会变成闭包。
什么情况下使用闭包?
当我们在开发过程中,需要一个全局变量的时候,我们一般会在文件中创建一个变量来进行调用,例如:
GLOBAL = "全局变量"
但全局变量公开之后,会变得所有人都可以调用,如果不想被其他人调用,我们就可以将变量放到闭包中,这样变量会长期存储在内存中且无法被外部访问。
# 简单的闭包
def closure(param):
def inner():
print(param)
return inner
二、调用外部函数
如果仅是需要调用外部的函数,其实在python中非常简单,只需要使用importlib.util,如下:
spec = importlib.util.spec_from_file_location(
name='test',
location="xxx/xxx/xxx/test.py"
)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
我们仅仅需要知道文件路径及模块名即可将模块进行调用。
如果是其他路径模块调用,需要该模块项目中其他的方法或者类,需要将模块的路径加到系统路径下:sys.path.append(“xxxxx”)
三、实现逻辑
我们的逻辑很简单,当我们需要一个外部的函数调用时,将路径获取,并通过路径获取模块,然后如果文件进行修改,我们就把我们的模块进行更新,使用最新的方法,具体实现如下:
def call(py_file=""):
if not os.path.exists(py_file): # 判断文件是否存在
raise Exception("Py file does not exist")
if not py_file.endswith("py") and not py_file.endswith("pyc"): # 文件后缀是否正确
raise Exception("Py file type error")
py_file = py_file.replace("\\", "/") # 将路径统一为/
module_name = py_file.split('/')[-1] # 获取咱们的模块名称
if len(module_name.split(".")) > 0:
module_name = module_name.split(".")[0] # 获取咱们的模块名称
spec = importlib.util.spec_from_file_location(
name=module_name,
location=py_file
)
module = importlib.util.module_from_spec(spec) # 模块导入
spec.loader.exec_module(module) # 模块可以调用
module_dict = {
"module": module,
"update_time": time.strftime("%Y%m%d%H%M%S", time.localtime(os.stat(py_file).st_mtime))
} # 用来获取module及判断它的文件修改时间
def inner(**kwargs):
try:
update_time_str = time.strftime("%Y%m%d%H%M%S", time.localtime(os.stat(py_file).st_mtime))
except Exception as e:
raise e
if module_dict.get("update_time") != update_time_str: # 当前文件修改时间改变,则我们模块需要重新加入
spec.loader.exec_module(module_dict["module"])
module_dict["update_time"] = update_time_str
return module_dict["module"].test_func(**kwargs) # 外部模块的函数
return inner
调用测试
if __name__ == '__main__':
f1 = call("xxxxx/xxx/xxxxx/xxxx/test.py")
while True:
print(f"{time.strftime('%H:%M:%S', time.localtime())} {f1(tt='我是主函数')}")
time.sleep(2)
另一个模块方法:
def test_func(msg):
return msg + " 其他模块方法"
当我们改变另一个模块的方法时:
def test_func(msg):
return msg + " 其他模块方法,我改变了方法"