Python 类型提示:允许的对象列表(不是文字)

问题描述 投票:0回答:2

假设我有一个函数

foo(f)
,其中
f
应该是
np.sin
np.cos
之一。输入提示的正确方法是什么?

import numpy as np
def foo(f: Literal[np.sin, np.cos]):
    ...

看起来不错,但是

np.sin
np.cos
实际上不是文字,所以我的 linter 抱怨了。

python type-hinting
2个回答
0
投票

你可以直接写

import numpy as np
def foo(f: np.sin | np.cos):
    ...

0
投票

我想说 np.float64 是正确的类型。原因是这就是这两个函数返回的结果。

您可以这样检查类型:

import numpy as np


x = np.sin(100)
print(type(x))

两者都返回:

<class 'numpy.float64'>
<class 'numpy.float64'>

所以函数应该是这样的:

def foo(f: np.float64):
    ''' takes in a numpy sin or cos and does something 
    
    args:
        f: numpy sin or cos

    retrurn:
        something
    
    '''
    
    return


© www.soinside.com 2019 - 2024. All rights reserved.