Home > database >  what is the _correct_ way to write "a or b" kind of type hints in docstring?
what is the _correct_ way to write "a or b" kind of type hints in docstring?

Time:09-25

I have an argument which is either "E" or "H".

def my_func(name):
    """
    Parameters
    ----------
    name : str
    """

To specify it's either 'E' or 'H' I've seen people writing:

    name : {'E', 'H'}
    name : ['E', 'H']
    name : ['E' | 'H']
    name : Union['E', 'H']
    name : 'E' or 'H'

Or, putting those on the second line:

    name : str
        {'E', 'H'}
    name : str
        ['E', 'H']
    name : str
        ['E' | 'H']
    name : str
        Union['E', 'H']
    name : str
        'E' or 'H'

which one of the above is correct?

If it's int or float, which one of the following is correct?

  param : int or float
  param : Union[int, float]
  param : [int | float]
  param : {int, float}

CodePudding user response:

There isn't any correct way IMHO, but as I can see that uses a lot of these ways.

For pd.DataFrame.apply, there are:

axis : {0 or ‘index’, 1 or ‘columns’}, default 0

result_type : {‘expand’, ‘reduce’, ‘broadcast’, None}, default None

And for pd.DataFrame.aggregate:

func : function, str, list or dict

And for a array, np.array has:

order : {‘K’, ‘A’, ‘C’, ‘F’}, optional

And for np.zeros you got:

shape : int or tuple of ints

And typing.Union is also surely often used.

All of these are considerably correct, these ones and uses are considered more common.

  • Related