Skip to content

Instantly share code, notes, and snippets.

@L3viathan
Created July 21, 2024 18:32
Show Gist options
  • Save L3viathan/b1fbe8ad6d72a24803c505fd2077b5c7 to your computer and use it in GitHub Desktop.
Save L3viathan/b1fbe8ad6d72a24803c505fd2077b5c7 to your computer and use it in GitHub Desktop.
Add intersection types to Python
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