-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Possible to define a generic property? #8440
Comments
Maybe you can get something like this to work by using a protocol with |
Hi JukkaL, thanks for coming back to me, I managed to create a from typing import Generic, TypeVar, Optional, Callable, Any
T = TypeVar("T")
class Property(property, Generic[T]):
"""Generic implementation of a property.
Allows us to provide type annotations on top of builtin properties.
"""
def __init__(
self,
fget: Optional[Callable[[Any], Any]] = None,
fset: Optional[Callable[[Any, Any], None]] = None,
fdel: Optional[Callable[[Any], None]] = None,
doc: Optional[str] = None,
) -> None:
super().__init__(fget, fset, fdel, doc)
def __get__(self, obj: Any, objtype=None) -> T:
return super().__get__(obj, objtype)
def __set__(self, obj: Any, value: T) -> None:
super().__set__(obj, value)
def __delete__(self, obj: Any) -> None:
super().__delete__(obj) Are there any improvements you might suggest to the above? Otherwise I think I'm quite happy with this approach for now, so can close this. :) |
Feature Request, or just a clarification of whats possible, using python 3.6.10, Mypy 0.761
Hi folks,
I have some code which uses a class decorator to mutate a collection of callables, into a collection of properties, which has recently lead me down a bit of a garden path with mypy.
I believe that I can refactor my work to make use of a generic property, and achieve a similar net goal. What I would quite like to create, would be something loosely like a Generic Protocol that describes a property. With that I'd be able to define something approximately like this (I may need to clarify a bit further):
Whilst I believe that simple properties are now supported by mypy, I've been having a collection of issues with dynamically using the
property()
builtin.I wonder whether I would be able to create a property Protocol that supports generics, to achieve something like the above?
Any advice much appreciated, and thanks for your time in advance!
Possibly related: #8083
The text was updated successfully, but these errors were encountered: