【发布时间】:2021-10-31 12:52:27
【问题描述】:
标题可能有点模棱两可,因为我不确定如何准确表达我想要做的事情。
我想在 python 中从 C++ 复制类似这种模式:
template<typename T>
struct Foo
{
using t = T; // Alias T so it can be used in Bar
};
template<typename T>
struct Bar
{
// The type T from Foo<T> can be used as a return type here
typename T::t fn()
{
// do something that returns T::t
}
};
int main(){
// x is determined to be a float
auto x = Bar<Foo<float>>().fn();
};
在 python 方面,我想将泛型类型 Bar[T] 特化为另一个特化类型 Foo[T],然后使用用于特化 Foo 的类型在 Bar 中键入提示。
类似
from typing import TypeVar, Generic
T = TypeVar("T")
class Foo(Generic[T]):
...
class Bar(Generic[Foo[T]]): # <-- This is illegal
def fn(self) -> T:
...
# In the following, I would like the type checker to know that x is an int.
x = Bar[Foo[int]]().fn()
如果我们有类似的东西,我知道在创建 Bar 的实例时可以推断出这种关系
class Bar(Generic[T]):
def __init__(self, foo: Foo[T]):
...
但这并不真正适合我目前的问题。
我希望能够创建一系列专业化Foo[T]、Bar[T]、Baz[T] 等,而无需多次重复T。在我的实际用例中,这些类型更像Foo[R, S, T],并且重复这些类型非常繁琐且容易出错,并且从概念上讲,类Bar、Baz 等被认为不依赖于T 类型,而是而是一种特殊类型的Foo[T]。
所以如果有能力做类似的事情就好了
MyFoo = Foo[int]
MyBar = Bar[MyFoo]
MyBaz = Baz[MyFoo]
【问题讨论】:
-
可以尝试使用
typing.Union,如Union[int, str] -
不幸的是,我认为 Python 当前的打字语法不可能做到这一点。
标签: python type-hinting python-typing