英文:
Expected no type arguments for class "Self"
问题
我有一个通用类,其中有一个next
方法,该方法返回一个参数化为不同类型变量的自身实例。
我可以使用"
来指定next
方法的返回类型,以引用类本身:
DataIn = TypeVar('DataIn')
DataOut = TypeVar('DataOut')
@dataclass
class Msg(Generic[DataIn]):
source: str
data: DataIn
def next(self, data: DataOut) -> "Msg[DataOut]":
"""
创建一个具有相同源但不同数据的新消息
"""
return Msg(source=self.source, data=data)
我想使用PEP 673中的Self
类型来避免使用"
:
def next(self, data: DataOut) -> Self[DataOut]:
但是在Pylance / Pyright中无法通过类型检查:
Expected no type arguments for class "Self"
文档中说:“Self也可以在通用类方法中使用”,但没有显示这个特定的用例。
它是否被支持?
英文:
I have a generic class, with a next
method which returns an instance of itself parameterized to a difference type variable.
I can specify the next
method's return type using "
to reference the class itself:
DataIn = TypeVar('DataIn')
DataOut = TypeVar('DataOut')
@dataclass
class Msg(Generic[DataIn]):
source: str
data: DataIn
def next(self, data: DataOut) -> "Msg[DataOut]":
"""
Create a new message with the same source but different data
"""
return Msg(source=self.source, data=data)
I would like to use the PEP 673 Self
type to avoid the "
':
def next(self, data: DataOut) -> Self[DataOut]:
But that fails to type check in Pylance / Pyright:
Expected no type arguments for class "Self"
The docs say: "Self can also be used in generic class methods", but don't show this specific use case.
Is it supported?
答案1
得分: 0
这是不支持的,而且是有意不支持的。在通用类型的情况下,Self
(在普通方法中,而不是类方法中)指的是已经参数化的实例。
引用你提供的文档(即相同的部分):
注意,我们拒绝使用带有类型参数的
Self
,比如Self[int]
。这是因为它会对self参数的类型产生歧义,并引入不必要的复杂性:
class Container(Generic[T]):
def foo(
self, other: Self[int], other2: Self,
) -> Self[str]: # 被拒绝
...
在这种情况下,我们建议为self使用显式类型:
class Container(Generic[T]):
def foo(
self: Container[T],
other: Container[int],
other2: Container[T]
) -> Container[str]: ...
英文:
This is not supported, and not supported intentionally. In case of generic types Self
refers (in regular methods - not classmethods) to some already parametrized instance.
Quoting the docs (even the same section) that you linked:
> Note that we reject using Self
with type arguments, such as Self[int]
. This is because it creates ambiguity about the type of the self parameter and introduces unnecessary complexity:
class Container(Generic[T]):
def foo(
self, other: Self[int], other2: Self,
) -> Self[str]: # Rejected
...
> In such cases, we recommend using an explicit type for self:
class Container(Generic[T]):
def foo(
self: Container[T],
other: Container[int],
other2: Container[T]
) -> Container[str]: ...
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论