【发布时间】:2021-01-14 11:42:21
【问题描述】:
我想设计一个python decorator,它接受一个经过修饰的函数并将其传递给另一个函数。这是我正在尝试做的代码解释:
def run_decorator(run_batch):
# inner function can access the outer local
# functions like in this case "func"
def check(command_to_run):
@functools.wraps(command_to_run)
def wrapper(*args, **kwargs):
batch_json_path = kwargs['batch_json_path']
batch_name = kwargs['batch_name']
folder_path = kwargs['folder_path']
if batch_json_path is not None:
if batch_present(batch_json_path, batch_name):
run_batch(batch_json_path, command_to_run, batch_name)
return wrapper
return check
def run_batch(batch_abs_path, command_to_run, batch_name=None):
with open(batch_abs_path) as json_file:
variant = ...
tag_data = ...
command_to_run(variant, batch_name, tag_data)
@run_decorator(run_batch=run_batch)
def load_tag_for_variant(variant, batch_name, tag_data):
这样的行为可能实现吗?任何建议将不胜感激。
【问题讨论】:
-
对我来说,代码非常合理,应该可以工作。你的问题到底是什么?
-
我猜主要的问题是我不完全确定如何同时将参数传递给两个函数(run_batch 和 command_to_run)。
-
我需要将 3 个参数传递给装饰器:batch_json_path、batch_name 和 folder_path,它们不是 load_tag_for_variant 函数的参数,但应该在程序运行时以某种方式输入到装饰器/load_tag_for_variant。