Код: Выделить всё
class MyModule(Module):
a = Connector(float)
b = Connector(Union[float, str, int])
c = Connector(str)
@c.callback
def get_c(self):
return f'This is a string with {self.a} and {self.b}'
Код: Выделить всё
from typing import TypeVar, Generic, overload, Any, reveal_type, Callable, Union
T = TypeVar('T')
class Func(Generic[T]):
_type: type[T]
@overload
def __init__(self, _type: type[T]) -> None: ...
@overload
def __init__(self, _type: Any) -> None: ...
def __init__(self, _type: type[T] | Any):
self._type = _type
def __call__(self, value: T) -> T:
return value
f1 = Func(float)
a = f1(1.0)
reveal_type(f1) # revealed type is Func[float]
reveal_type(a) # revealed type is float
f2 = Func[float|str](float|str)
b = f2('a')
reveal_type(f2) # revealed type is Func[Union[float, str]]
reveal_type(b) # revealed type is Union[float, str]
f3 = Func(Union[float, str]) # type: ignore
c = f3('a')
reveal_type(f3) # revealed type is Func[Any]
reveal_type(c) # revealed type is Any
Есть идеи? Текущий выбор для Type[T] | Любой, который я позаимствовал у TypeAdapter от pydantic. Я видел это: Как мне ввести подсказку для переменной, значение которой само по себе является подсказкой типа? но заменив Type[T] | Любой с более длинным объединением дает мне тот же результат, что и mypy. Кроме того, похоже, этот вариант не специализируется на использовании T.
Подробнее здесь: https://stackoverflow.com/questions/798 ... low-unions
Мобильная версия