@@ -46,42 +46,71 @@ def f():
46
46
y: Any = " not an Any" # error: [invalid-assignment]
47
47
```
48
48
49
- ## Subclass
49
+ ## Subclasses of ` Any `
50
50
51
51
The spec allows you to define subclasses of ` Any ` .
52
52
53
- ` Subclass ` has an unknown superclass, which might be ` int ` . The assignment to ` x ` should not be
53
+ ` SubclassOfAny ` has an unknown superclass, which might be ` int ` . The assignment to ` x ` should not be
54
54
allowed, even when the unknown superclass is ` int ` . The assignment to ` y ` should be allowed, since
55
55
` Subclass ` might have ` int ` as a superclass, and is therefore assignable to ` int ` .
56
56
57
57
``` py
58
58
from typing import Any
59
59
60
- class Subclass (Any ): ...
60
+ class SubclassOfAny (Any ): ...
61
61
62
- reveal_type(Subclass .__mro__ ) # revealed: tuple[Literal[Subclass ], Any, Literal[object]]
62
+ reveal_type(SubclassOfAny .__mro__ ) # revealed: tuple[Literal[SubclassOfAny ], Any, Literal[object]]
63
63
64
- x: Subclass = 1 # error: [invalid-assignment]
65
- y: int = Subclass()
66
-
67
- def _ (s : Subclass):
68
- reveal_type(s) # revealed: Subclass
64
+ x: SubclassOfAny = 1 # error: [invalid-assignment]
65
+ y: int = SubclassOfAny()
69
66
```
70
67
71
- ` Subclass ` should not be assignable to a final class though, because ` Subclass ` could not possibly
72
- be a subclass of ` FinalClass ` :
68
+ ` SubclassOfAny ` should not be assignable to a final class though, because ` SubclassOfAny ` could not
69
+ possibly be a subclass of ` FinalClass ` :
73
70
74
71
``` py
75
72
from typing import final
76
73
77
74
@final
78
75
class FinalClass : ...
79
76
80
- f: FinalClass = Subclass() # error: [invalid-assignment]
77
+ f: FinalClass = SubclassOfAny() # error: [invalid-assignment]
78
+
79
+ @final
80
+ class OtherFinalClass : ...
81
+
82
+ f: FinalClass | OtherFinalClass = SubclassOfAny() # error: [invalid-assignment]
83
+ ```
84
+
85
+ A subclass of ` Any ` can also be assigned to arbitrary ` Callable ` types:
86
+
87
+ ``` py
88
+ from typing import Callable, Any
89
+
90
+ def takes_callable1 (f : Callable):
91
+ f()
92
+
93
+ takes_callable1(SubclassOfAny())
94
+
95
+ def takes_callable2 (f : Callable[[int ], None ]):
96
+ f(1 )
97
+
98
+ takes_callable2(SubclassOfAny())
99
+ ```
100
+
101
+ A subclass of ` Any ` cannot be assigned to literal types, since those can not be subclassed:
102
+
103
+ ``` py
104
+ from typing import Any, Literal
105
+
106
+ class MockAny (Any ):
107
+ pass
108
+
109
+ x: Literal[1 ] = MockAny() # error: [invalid-assignment]
81
110
```
82
111
83
- A use case where this comes up is with mocking libraries, where the mock object should be assignable
84
- to any type:
112
+ A use case where subclasses of ` Any ` come up is in mocking libraries, where the mock object should
113
+ be assignable to (almost) any type:
85
114
86
115
``` py
87
116
from unittest.mock import MagicMock
0 commit comments