1

I extended a method with an additional string parameter (average):

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

So the normal usage would be something like:

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

Coming from a review on Github, the reviewer suggested to support multiple values as well: average=['micro', 'weighted', 'macro']

What would be an appropriate way to solve this in Python? I know that the parameter can have any type. But how to handle a potential call with a list of strings? And what would be the type of the parameter? Union[str, List[str]]?

Currently I only expect a string, which is straight forward. But in case I also allow a list of strings, should I check the type first with type(average) and then process the values accordingly? Is there an elegant way of transforming the parameter variable into a uniform type, something like averages=listify(average), which takes either a string or a list of strings and always returns a list of strings?

martineau
  • 119,623
  • 25
  • 170
  • 301
Alexander Pacha
  • 9,187
  • 3
  • 68
  • 108

1 Answers1

2

Here is an example from pandas:

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

This is code from the method pandas.DataFrame.reset_index(level=None, drop=False, inplace=False, col_level=0, col_fill='') where level is expected to be a int, str, tuple, or list, default None. This simple code simply makes sure that the parameter is now stored in a list, regardless of how it was given.

Eran
  • 844
  • 6
  • 20