1

假设我们创建了一个在Python 3.10中调用的通用Union类型ResultData

from __future__ import annotations

from dataclasses import dataclass
from typing import TypeVar, Generic, Union
from typing import _SpecialForm, _GenericAlias

@dataclass(frozen=True)
class Error:
    description: str

S = TypeVar('S')
ResultData = S | Error

请注意,在这种情况下,我使用的是新的 Python 3.10 Union 语法

然后当试图继承类以添加一些方法(比如来自 Monad 的方法)时,问题就来了:

T = TypeVar('T')
class Result(ResultData[T]):
    def __init__(self):

通过声明这个类,它会抛出以下错误:

    class Result(ResultData[T]):
TypeError: _SpecialForm.__init__() takes 2 positional arguments but 4 were given

似乎 Union 类型继承自以下两个类:_SpecialForm_GenericAlias.

_GenericAlias有 4 个参数作为构造函数,而_SpecialForm只有两个。我的猜测_SpecialForm构造函数是使用_GenericAlias构造函数调用的,因此会导致错误。

我尝试使用以下代码解决此问题:

T = TypeVar('T')
class Result(ResultData[T]):
    def __init__(self):
        super(_SpecialForm, self).__init__(self._getitem)
        super(_GenericAlias, self).__init__(self.origin, self.params, self.inst, self.name)

但是我仍然遇到同样的错误。

4

0 回答 0