8000 Added new impossible intersect example · CarliJoy/intersection_examples@e76e146 · GitHub
[go: up one dir, main page]

Skip to content

Commit e76e146

Browse files
committed
Added new impossible intersect example
1 parent bf0f7a5 commit e76e146

File tree

2 files changed

+40
-8
lines changed

2 files changed

+40
-8
lines changed

examples/impossible.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
from intersection_examples import Intersection
2+
3+
test = Intersection[int, str]

intersection_examples/__init__.py

Lines changed: 37 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -40,11 +40,39 @@ def get_possible_methods(method: Callable) -> list[Callable]:
4040
return overloads
4141

4242

43+
base_types = (
44+
int,
45+
float,
46+
str,
47+
bytes,
48+
bytearray,
49+
bool,
50+
type,
51+
BaseException,
52+
set,
53+
list,
54+
tuple,
55+
range,
56+
memoryview,
57+
dict,
58+
frozenset,
59+
complex,
60+
)
61+
62+
4363
class Intersection:
4464
__intersects__: set[type[object]]
4565

4666
def __init__(self, *intersects: type[object]) -> None:
4767
self.__intersects__ = set(reversed(intersects))
68+
for i in self.__intersects__:
69+
if not hasattr(i, "mro"):
70+
raise ValueError(f"mro not found for {i}")
71+
for base_type in base_types:
72+
if base_type in i.mro():
73+
raise TypeError(
74+
f"Type {i} found to derive from base type {base_type}"
75+
)
4876
self._test_lsp()
4977

5078
def __class_getitem__(cls, key):
@@ -55,14 +83,15 @@ def _test_lsp(self):
5583
signatures: dict[str, list[Signature]] = {}
5684
for i in self.__intersects__:
5785
# Resolve basic annotations, ensuring no clashes
58-
for annotation_name, annotation_type in i.__annotations__.items():
59-
if annotation_name in intersected_attrs:
60-
if annotation_type != intersected_attrs[annotation_name]:
61-
raise TypeError(
62-
f"Attribute {annotation_name} has type clash on {annotation_type} vs {intersected_attrs[annotation_name]}"
63-
)
64-
else:
65-
intersected_attrs[annotation_name] = annotation_type
86+
if hasattr(i, "__annotations__"):
87+
for annotation_name, annotation_type in i.__annotations__.items():
88+
if annotation_name in intersected_attrs:
89+
if annotation_type != intersected_attrs[annotation_name]:
90+
raise TypeError(
91+
f"Attribute {annotation_name} has type clash on {annotation_type} vs {intersected_attrs[annotation_name]}"
92+
)
93+
else:
94+
intersected_attrs[annotation_name] = annotation_type
6695

6796
for method_name in dir(i):
6897
method = getattr(i, method_name)

0 commit comments

Comments
 (0)
0