-
Hello, i have a question about of the from __future__ import annotations
import typing
T = typing.TypeVar("T")
def field(*, converter: typing.Callable[[typing.Any], typing.Any]) -> typing.Any: ...
class From(typing.Generic[T]):
def __new__(cls, _: T, /) -> typing.Any: ...
class Field(typing.Generic[T]):
if typing.TYPE_CHECKING:
@typing.overload
def __get__(self, instance: None, owner: type[Model]) -> T: ...
@typing.overload
def __get__(self, instance: Model, owner: type[Model]) -> T: ...
def __get__(
self,
instance: Model | None,
owner: type[Model],
) -> Field[T] | T: ...
@typing.dataclass_transform(field_specifiers=(field,))
class Model: ...
class User1(Model):
id: int
is_bot: bool
first_name: str
last_name: Field[str] = field(converter=From[str])
user1 = User1(...)
typing.reveal_type(user1.last_name) # Type of "user1.last_name" is "Field[str]"
class User2(Model):
id: int
is_bot: bool
first_name: str
last_name: Field[str]
user2 = User2(...)
typing.reveal_type(user2.last_name) # Type of "user2.last_name" is "str" So, in this code there is a |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
Please refer to this part of the typing spec for details about how type checkers handle the The type annotation that you use for a dataclass attribute with a converter should be the type returned by the converter. I can't tell from your code sample what type that is in this case because the If you annotate |
Beta Was this translation helpful? Give feedback.
Here's what I mean when I say that the
__get__
method of a descriptor object isn't invoked if the descriptor object is an instance variable.What is the type of the object that your converter function returns? That's the type that should appear in the annotation for
last_name
attribute.