python - 创建自己的可选版本
问题描述
我的代码中有这样的东西:
Undefined = Literal['__undefined_attr__']
undefined: Undefined = '__undefined_attr__'
def funkc(
foo: Union[str, Undefined] = undefined,
bar: Union[int, Undefined] = undefined,
baz: Union[str, Undefined] = undefined,
boo: Union[float, Undefined] = undefined,
# ... lots more args like that with many different types
):
if foo is not undefined:
...
if bar is not undefined:
...
... # etc.
现在,如果我可以使用 None 作为默认值,这一切都会变得更简单,例如:
def funkc(
foo: Optional[str] = None,
bar: Optional[int] = None,
baz: Optional[str] = None,
boo: Optional[float] = None,
# ... lots more args like that with many different types
):
if foo is not None:
...
if bar is not None:
...
... # etc.
所以我想我可以创建自己的类型快捷方式,可以像这样使用:
def funkc(
foo: OptionallyDefined[str] = undefined,
bar: OptionallyDefined[int] = undefined,
baz: OptionallyDefined[str] = undefined,
boo: OptionallyDefined[float] = undefined,
# ... lots more args like that with many different types
):
if foo is not undefined:
...
if bar is not undefined:
...
... # etc.
但实际上创造这个OptionalylDefined
东西是在逃避我。这可能与 mypy 吗?
解决方案:
感谢user2357112 支持 Monica 的回答,这就是我最终使用的:
class Undefined:
instance = None
def __new__(cls, *args, **kwargs) -> "Undefined":
"""Singleton, just in case..."""
if not cls.instance:
cls.instance = super().__new__(cls, *args, **kwargs) # type: ignore
return cls.instance
undefined = Undefined()
ArgType = TypeVar("ArgType")
OptionallyDefined = Union[ArgType, Undefined]
def funkc(...):
if foo is not undefined:
...
解决方案
我这里没有 mypy,所以我无法对此进行测试,但以下应该可以工作。(确保使用 mypy 进行测试,而不仅仅是运行它):
T = typing.TypeVar('T')
OptionallyDefined = typing.Union[T, Undefined]
def funkc(
foo: OptionallyDefined[str] = undefined,
...
):
...
您自己的 TypeVar 尝试失败,因为您同时undefined
以与typing.Literal
.
顺便说一句,这种定义和使用undefined
的方式并不安全。MyPy 将认为任何'__undefined_attr__'
字符串都是 type 的有效值Undefined
,但您的is
比较将拒绝某些字符串并允许其他字符串,具体取决于实现细节和任何特定字符串的来源。我会编写一个类并使用该类的实例undefined
,而不是使用字符串和typing.Literal
。
推荐阅读
- python - 根据条件在python中组合数据框的行
- directus - 如何使用directus API中的父ID从自引用(分层)表中获取树结构
- python - 使用 Geoplot 将颜色固定到 bin
- git - 如何获取 git/GITHUB 中所有已删除的未合并分支的列表?
- angular - 为什么我的 BehaviorSubject 在我更改页面时会丢失值?
- c# - 交叉编译的 c# 套接字程序,适用于 win,但不适用于 mac
- python - 如何修改 sns.histplot 中的核密度估计线
- azure - AzureDevops 无法连接到 TestComplete
- azure - 使用通用证书而不是特定于应用程序的 Azure AD SAML
- python - 来自多对多字段的序列化程序额外字段