Skip to content

Instantly share code, notes, and snippets.

@Spitfire1900
Last active August 27, 2025 17:26
Show Gist options
  • Save Spitfire1900/551a6219ade8754bcdf92c6b38d97207 to your computer and use it in GitHub Desktop.
Save Spitfire1900/551a6219ade8754bcdf92c6b38d97207 to your computer and use it in GitHub Desktop.
Restrict type 'T' to be the exact type passed to constraint()
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