首页 > 解决方案 > 创建自己的可选版本

问题描述

我的代码中有这样的东西:

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:
        ...

标签: pythonmypypython-typing

解决方案


我这里没有 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


推荐阅读