Last active
August 27, 2025 17:26
-
-
Save Spitfire1900/551a6219ade8754bcdf92c6b38d97207 to your computer and use it in GitHub Desktop.
Restrict type 'T' to be the exact type passed to constraint()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from __future__ import annotations | |
class _ExactType[T]: | |
def __init__(self, tp: type[T]) -> None: | |
self.tp = tp | |
def constraint[T](tp: type[T]) -> _ExactType[T]: | |
return _ExactType(tp) | |
class _Option[T]: | |
... | |
def make_option[T](tp: _ExactType[T], *, default: T) -> _Option[T]: | |
raise NotImplementedError | |
class Animal(): | |
... | |
class Cat(Animal): | |
... | |
# ok | |
make_option(constraint(str), default='') | |
make_option(constraint(int), default=0) | |
make_option(constraint(Animal), default=Cat()) | |
# error | |
make_option(int, default=0) | |
make_option(constraint(str), default=0) | |
make_option(constraint(Cat), default=Animal()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment