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

Viewed 131

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}
3 Answers

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.

I would allways use the Union class from typehint like this:


from typing import Union

def my_func(name: Union[a, b]):
    """
    Parameters
    ----------
    name : a | b
    """
    pass

´´´

For future reference, here is a cheat sheet of the "a or b" type hints in docstring that are correctly recognized by pycharm to check inconsistencies when you pass arguments:

name : str or dict
name : str, dict
name : str | dict
name : {str or dict}
name : {str, dict}
name : {str | dict}
name : 'E', 123   # recognized as str or int
name : {'E', 123}  # recognized as str or int
name : list[float or dict]
name : list[float, dict]  # this will be understood as a list of a float and a dict, not as List[Union[float, dict]]
name : list[float | dict]

The following can't be processed correctly by pycharm:

name : [str or dict]
name : [str, dict]
name : [str | dict]
name : Union[str, dict]
name : 'E' or 123
name : 'E' | 123
name : {'E' or 123}
name : {'E' | 123}
name : ['E' or 123]
name : ['E', 123]  # recognized as int
name : ['E' | 123]
list{float or dict}
list{float, dict}  # recognized as dict
list{float | dict}
list of ***  # No matter what you put here, e.g. list of {int, float}, it won't be corrected processed.#

# none of the expressions I can come up with can express "list of elements that are either 123 or 'abc'".
Related