@@ -10,6 +10,31 @@ from os import PathLike
10
10
from typing import AbstractSet , Any , Container , Generic , Iterable , Protocol , TypeVar , Union
11
11
from typing_extensions import Final , Literal , final
12
12
13
+ _WU = TypeVar ('_WU' )
14
+
15
+ class WeakUnion (Generic [_WU ], Any ):
16
+ """
17
+ Some functions can return different types depending on passed arguments. e.g.
18
+
19
+ * `builtins.open(name, 'rb')` returns `io.BufferedReader`, whereas
20
+ * `builtins.open(name, 'wb')` returns `io.BufferedWriter`.
21
+
22
+ Typeshed attempts to model such scenarios accurately via `@typing.overload`,
23
+ however with with such overloaded functions there is always the case
24
+ that the return type cannot be determined statically, e.g:
25
+
26
+ def my_open(name: str, mode: str):
27
+ return open(name, mode)
28
+
29
+ In such cases typeshed currently returns Any. While a Union return would be
30
+ more accurate that would require all existing code that depends on the Any
31
+ (and asserts the type safety in some other way) to be updated. WeakUnion lets
32
+ typeshed annotate the semantic return type of such overloads in a backwards
33
+ compatible manner. Type checkers that do not know about this typeshed-specific
34
+ type will just treat it as Any, whereas tooling that knows about it can use
35
+ the additional information to provide more type safety or better autocompletion.
36
+ """
37
+
13
38
_KT = TypeVar ("_KT" )
14
39
_KT_co = TypeVar ("_KT_co" , covariant = True )
15
40
_KT_contra = TypeVar ("_KT_contra" , contravariant = True )
0 commit comments