setattr type conversions #1093
Unanswered
hmc-cs-mdrissi
asked this question in
Q&A
Replies: 1 comment 4 replies
-
It's hard to say for certain without knowing which library you're talking about, but it seems likely that the library is accomplishing this kind of magic using some kind of descriptor. Luckily, mypy has a pretty good grasp of the descriptor protocol, so you should be able to model this kind of behaviour like this: ### STUB ###
from typing import Any, TypeVar
_T = TypeVar("_T")
class ListWrapper: ...
class MyDescriptor:
def __get__(self, obj: _T, objtype: type[_T] | None = ...) -> ListWrapper: ...
def __set__(self, obj: Any, value: list[str]) -> None: ...
class Model:
x: MyDescriptor
### RUNTIME ###
class MyModel(Model):
def __init__(self, x: list[str]) -> None:
self.x = x
reveal_type(self.x) # Revealed type is "__main__.ListWrapper"
self.x = 6 # error: Incompatible types in assignment (expression has type "int", variable has type "List[str]") See it in action on mypy playground here. |
Beta Was this translation helpful? Give feedback.
4 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
One interesting type behavior I stumbled on with one library is it auto converts certain attributes to a different type when set in that class/subclass. Some example code,
How would I write a stub for Model class that indicates this behavior? Is it possible to describe? Exact behavior is roughly setting attribute to a list becomes ListWrapper, dict to DictWrapper, other types are left untouched. While list/ListWrapper behave similarly there are cases where difference matters (runtime type introspection libraries being one).
Beta Was this translation helpful? Give feedback.
All reactions