支持单个字符串和数组作为一个参数

Support single string and array as one parameter

I extended a method 加上一个额外的字符串参数(平均):

def classification_report(y_true, y_pred, labels=None, target_names=None,
                          sample_weight=None, digits=2, average='weighted'):

所以正常的用法是这样的:

classification_report(y_true, y_pred, average='micro')

来自 Github 的评论,评论者建议也支持多个值:average=['micro', 'weighted', 'macro']

在 Python 中解决此问题的合适方法是什么?我知道参数可以有任何类型。但是如何处理带有字符串列表的潜在调用呢?参数的类型是什么? Union[str, List[str]]?

目前我只需要一个字符串,它很简单。但是如果我也允许一个字符串列表,我应该先用 type(average) 检查类型然后相应地处理值吗?有没有一种优雅的方法可以将参数变量转换为统一类型,例如 averages=listify(average),它采用字符串或字符串列表,并且总是 returns 字符串列表?

这是来自 pandas 的示例:

if level is not None:
        if not isinstance(level, (tuple, list)):
            level = [level]

这是来自方法 pandas.DataFrame.reset_index(level=None, drop=False, inplace=False, col_level=0, col_fill='') 的代码,其中级别预计为 int, str, tuple, or list, default None。这个简单的代码只是确保参数现在存储在列表中,无论它是如何给出的。