Created
July 21, 2024 18:32
-
-
Save L3viathan/b1fbe8ad6d72a24803c505fd2077b5c7 to your computer and use it in GitHub Desktop.
Add intersection types to Python
This file contains 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
import typing | |
import fishhook | |
class IntersectionMeta(type): | |
def __instancecheck__(self, other): | |
return all(isinstance(other, t) for t in self.types) | |
def __repr__(self): | |
if hasattr(self, "types"): | |
return " & ".join(t.__name__ for t in self.types) | |
return "Intersection" | |
class Intersection(metaclass=IntersectionMeta): | |
def __class_getitem__(self, types): | |
new_cls = IntersectionMeta("Intersection", self.__bases__, {}) | |
new_cls.types = types | |
return new_cls | |
@fishhook.hook(type) | |
def __and__(self, other): | |
if issubclass(self, IntersectionMeta): | |
return Intersection[(*self.types, other)] | |
return Intersection[self, other] | |
typing.Intersection = Intersection |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment