GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — Allow Self or Self-like type arguments for generics · Issue #2276 · python/typing Open Labels topic: featureDiscussions about new features for Python's type annotationsDiscussions about new features for Python's type annotations Descriptionfrom contextlib import AbstractContextManager class ManagerA(AbstractContextManager): def __init__(self, x: int) -> None: self._x = x def __enter__(self) -> int: return self._x This can raise type check errors because from contextlib import AbstractContextManager class ManagerA(AbstractContextManager[int]): def __init__(self, x: int) -> None: self._x = x def __enter__(self) -> int: return self._x But what if we are not overriding the from contextlib import AbstractContextManager class ManagerB(AbstractContextManager): def __init__(self, x: int) -> None: self._x = x # Other methods are defined, but __enter__ is not overridden In this case, there is no great way to accurate type annotate it in order to reflect the fact that the If we were willing to mark this class as class ManagerB(AbstractContextManager["ManagerB"]): And that would work. But if we want to be able to subclass it, then this would no longer be accurate. Consider: from contextlib import AbstractContextManager from types import TracebackType from typing import Type class ManagerB(AbstractContextManager["ManagerB"]): def __init__(self, x: int) -> None: self._x = x # Other methods are defined, but __enter__ is not overridden def __exit__( self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None) -> bool | None: return None class SubManager(ManagerB): def harf(self) -> None: print("harf") with SubManager(1) as subman: subman.harf() This runs fine, but the type checker will rightly complain. The annotations indicate that It feels like it would be appropriate to use: class ManagerB(AbstractContextManager[Self]): But The feature I would like to see is some way to accurately handle non-final subclasses of Obviously this issue applies generally to generics -- this is just an obvious example since the Python implementation of that class makes it impossible to type annotate many of its subclasses. But ideally any solution would apply generally to generics -- essentially giving a way to use Activity
MetadataMetadataAssigneesLabelstopic: featureDiscussions about new features for Python's type annotationsDiscussions about new features for Python's type annotations ProjectsMilestoneRelationshipsDevelopmentIssue actions |
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |