gpt4 book ai didi

python - 如何创建其中一种类型作为参数提供的类型组合?

转载 作者:行者123 更新时间:2023-12-01 07:18:19 24 4
gpt4 key购买 nike

我需要类型组合的简写,其中一种类型作为参数提供。

示例:

class CustomType:
pass

# Shorthand
OptionalCustomType = Union[Optional[T], CustomType]

# Usage
def fun(x: OptionalCustomType[str]) -> str:
# Type of x should be equivalent to Union[None, CustomType, str]
if x is None:
return "None"
if x is CustomType:
return "Custom Type"
return "Some string"

最佳答案

您的代码示例基本上几乎按原样运行。您只需将 T 设为 typevar:

from typing import Optional, Union, TypeVar

class CustomType:
pass

T = TypeVar('T')
OptionalCustomType = Union[Optional[T], CustomType]

# This type-checks without an issue
def fun(x: OptionalCustomType[str]) -> str:
# Type of x should be equivalent to Union[None, CustomType, str]
if x is None:
return "None"
if x is CustomType:
return "Custom Type"
return "Some string"

y: OptionalCustomType[int]

# In mypy, you'll get the following output:
# Revealed type is 'Union[builtins.int, None, test.CustomType]'
reveal_type(y)

这种特殊技术被称为 generic type aliases .

关于python - 如何创建其中一种类型作为参数提供的类型组合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57841139/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com