如何为 python 中的函数创建模板?

how do i create a template for functions in python?

我在 python 中有一些共享相同结构的函数:

举几个例子:


def generate_report_1(eval_path, output_path):
   df = pd.read_csv(eval_path)
   missclassified_samples = df[df["miss"] == True]
   missclassified_samples.to_csv(output_path)


def generate_report_2(eval_path, output_path):
   df = pd.read_csv(eval_path)
   
   dict_df = df.to_dict()
   
   final_results = {}
   for name, metric in dict_df.items():
      # ... do some processing

   pd.DataFrame(final_results).to_csv(output_path)
   

在ruby中,我们可以使用块来暂停和return使用yield来执行函数。我想知道在 python 中完成此操作的良好做法,因为这是不希望出现的重复代码的情况。

谢谢。

不需要特殊的构造,只需要简单的 Python 函数。
唯一的技巧是将处理函数作为参数传递给报告函数,因此:

def generate_report(eval_path, processfunc, output_path):
   df = pd.read_csv(eval_path)
   result = processfunc(df)
   result.to_csv(output_path)

def process_1(df):
   return df[df["miss"] == True]

def process_2(df):
   dict_df = df.to_dict()
   final_results = {}
   for name, metric in dict_df.items():
      # ... do some processing
   return pd.DataFrame(final_results)

# and then:  
# generate_report(my_eval_path, process_1, my_output_path)