在Python 3中,我需要能够使用Callables及其所有参数作为上下文管理器的对象,这样,在调用这些方法/函数之前和之后,我可以执行某些操作并在这些预处理中准备的数据中调用方法本身行为,分别使用结果进行后处理。下面显示的使用带有方法列表的“执行”函数的方法只是我当前对方法的建议,但我愿意接受任何建议。
考虑一个标准上下文管理器
cm
实现为具有 __enter__
和 __exit__
方法的类:
class MyContextManager(object):
def __init__(self, ...):
:
def __enter__(self, ...):
:
return self
def __exit__(self, exc_type, exc_value, traceback):
:
return
def execute(...): # see comment above, just an idea. But how would this have to be implemented?
: ?
def preprocess(...): # see below, "callback" pre processing
:
def postprocess(...): # see below, "callback" prost processing
:
然后对于这样的电话:
with MyContextManager(data) as cm:
cm.execute([
OneHotEncode(data),
MergeTinyCategories(data, threshold=n)
])
我希望能够最终对执行方法列表中给出的所有方法执行类似“回调”的操作:
cm.preprocess(OneHotEncode, data)
res = OneHotEncode(data)
cm.postprocess(OneHotEncode, data)
cm.preprocess(MergeTinyCategories, data, threshold, n)
res = OneHotEncode(data)
cm.postprocess(MergeTinyCategories, data, threshold, n)
我还不知道如何为可调用参数编写此类“回调”。
问题是请求帮助在 Python 中实现上下文管理器,该管理器可以通过预处理和后处理回调执行可调用对象列表。
• 了解 Python 中的上下文管理器 • 实现预处理和后处理回调 • 使用可调用对象