Created
August 14, 2021 01:55
-
-
Save ixuuux/3ca3337d6775648b78f6f130cbf0c1f9 to your computer and use it in GitHub Desktop.
为函数增加结果回调的装饰器,支持多线程
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from functools import wraps | |
from typing import Callable | |
# 为函数增加结果回调功能 | |
def add_done_callback(call_func: Callable, *call_args, **call_kwargs): | |
""" 为函数增加结果回调功能的装饰器(主要为获取子线程运行结果) | |
def done_call(result, token): | |
print(result, token) | |
# 两种写法等效(推荐使用`lambda`匿名函数) | |
# @add_done_callback(call_func=done_call, token='demo') | |
@add_done_callback(call_func=lambda result: done_call(result, token='demo')) | |
def demo_func(): | |
# 其他内容 ... | |
return 'ok' | |
demo_func() | |
# ok demo | |
# 即使运行在线程中 | |
import threading | |
threading.Thread(target=demo_func).start() | |
:param call_func: 回调的函数 | |
:param call_args: 回调函数的其他位置参数 | |
:param call_kwargs: 回调函数的其他关键字参数 | |
:return: | |
""" | |
def decorate(func): | |
@wraps(func) | |
def wrapper(*args, **kwargs): | |
result = func(*args, **kwargs) | |
call_func(result, *call_args, **call_kwargs) | |
return result | |
return wrapper | |
return decorate |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment