将提示输入为多种类型的逻辑和

dsh*_*hin 5 python python-3.x

我知道这Union允许您指定多种类型的逻辑或。我想知道是否有办法为逻辑和做类似的事情,例如:

def foo(x: And[Bar, Baz]):
Run Code Online (Sandbox Code Playgroud)

我知道一种选择是明确定义一个继承自Barand的新类型Baz,如下所示:

class BarAndBaz(Bar, Baz):
    ...

def foo(x: BarAndBaz):
Run Code Online (Sandbox Code Playgroud)

在我的上下文中,该选项并不理想。

dsh*_*hin 4

基于 @deceze 和 @JimFasarakisHilliard 的有用评论:

出于所有意图和目的,您可以Union像使用 一样使用And,因为一个好的 IDE 应该自动完成类型Bar并且Baz如果您将变量声明为类型Union[Bar, Baz]

像这样的东西也将有助于提高可读性:

# IDE should treat And/Union equivalently; use And[T, U] to communicate
# that a variable is expected to be an instance of T *and* U, and
# Union[T, U] to communicate that it is expected to be an instance of T
# *or* U.
And = Union  
Run Code Online (Sandbox Code Playgroud)

在我的特定情况下,我的 IDE (PyCharm) 运行不正常,因为它需要更新和重新启动。