仅接受属性类型子集时的类型提示

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

假设我有一个类,其中一个属性有多种可能的类型,而一个函数仅适用于其中某些类型。

我如何类型提示该函数,以便它指定它只接受原始类接受的某些类型?

import dataclasses

@dataclasses.dataclass
class Foo:
    a: int | str

def plus_1_a(foo: Foo) -> None:
    """This will only work if foo.a is an int, not a string."""
    foo.a += 1
python mypy python-typing
1个回答
0
投票

考虑使

Foo
泛型化于
a
的类型。

import dataclasses
from typing import Generic, TypeVar

T = TypeVar("T", int, str)


@dataclasses.dataclass
class Foo(Generic[T]):
    a: T


def plus_1_a(foo: Foo[int]) -> None:
    """This will only work if foo.a is an int, not a string."""
    foo.a += 1
© www.soinside.com 2019 - 2024. All rights reserved.