python - 在文档字符串中写入 "a or b"类型提示的_正确_方式是什么?

标签 python typing python-typing docstring

我有一个参数是“E”或“H”。

def my_func(name):
    """
    Parameters
    ----------
    name : str
    """
要指定它是 'E' 或 'H' 我见过有人写:
    name : {'E', 'H'}
    name : ['E', 'H']
    name : ['E' | 'H']
    name : Union['E', 'H']
    name : 'E' or 'H'
或者,将它们放在第二行:
    name : str
        {'E', 'H'}
    name : str
        ['E', 'H']
    name : str
        ['E' | 'H']
    name : str
        Union['E', 'H']
    name : str
        'E' or 'H'
以上哪一项是正确 ?
如果是 intfloat ,以下哪一项是正确的?
  param : int or float
  param : Union[int, float]
  param : [int | float]
  param : {int, float}

最佳答案

恕我直言,没有任何正确的方法,但正如我所见使用了很多这些方式。
对于 pd.DataFrame.apply , 有:

axis : {0 or ‘index’, 1 or ‘columns’}, default 0
result_type : {‘expand’, ‘reduce’, ‘broadcast’, None}, default None
而对于 pd.DataFrame.aggregate :
func : function, str, list or dict

而对于 数组, np.array 已:
order : {‘K’, ‘A’, ‘C’, ‘F’}, optional
而对于 np.zeros 你得到了:
shape : int or tuple of ints
typing.Union肯定也经常使用。
所有这些都相当正确,这些用途被认为更常见。

关于python - 在文档字符串中写入 "a or b"类型提示的_正确_方式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69323028/

相关文章:

python - 如何合理利用线程池来完成多个海量计算任务?

python - 干净地处理多个变量的类型错误

python - 根据类启动参数决定调用哪个类方法

python - 如何指定返回类型与输入类型相同?

Python 输入 : best way to annotate parent class return subclass type object

python - 在没有 xrandr 的情况下获取 Python 中每个显示器的显示计数和分辨率

ios - "CL Typing Label "swift 库错误

python - 类型别名和 NewType 的区别

python - 我可以使用另一个函数的类型信息作为 Python 中的返回类型吗?

python - Python 3 中的 __total__ dunder 属性是什么意思?