12
12
Iterable ,
13
13
Iterator ,
14
14
List ,
15
+ Optional ,
15
16
Set ,
16
17
Sequence ,
17
18
Tuple ,
@@ -157,6 +158,7 @@ def __init__(
157
158
# dictionary of x->(y,z) for `from {x} import {y} as {z}`
158
159
# if {z} is None, then it shortens to `from {x} import {y}`
159
160
self .from_imports : Dict [str , Set [Tuple [str , str | None ]]] = defaultdict (set )
161
+ self .typing_extensions_min : Optional [Tuple [int , int ]] = None
160
162
161
163
# Comments
162
164
self .source_code_info_by_scl = {tuple (location .path ): location for location in fd .source_code_info .location }
@@ -165,6 +167,16 @@ def _import(self, path: str, name: str) -> str:
165
167
"""Imports a stdlib path and returns a handle to it
166
168
eg. self._import("typing", "Literal") -> "Literal"
167
169
"""
170
+ if path == "typing_extensions" :
171
+ stabilization = {
172
+ "Literal" : (3 , 8 ),
173
+ "TypeAlias" : (3 , 10 ),
174
+ }
175
+ assert name in stabilization
176
+ if not self .typing_extensions_min or self .typing_extensions_min < stabilization [name ]:
177
+ self .typing_extensions_min = stabilization [name ]
178
+ return "typing_extensions." + name
179
+
168
180
imp = path .replace ("/" , "." )
169
181
if self .readable_stubs :
170
182
self .from_imports [imp ].add ((name , None ))
@@ -864,8 +876,16 @@ def write(self) -> str:
864
876
# n,n to force a reexport (from x import y as y)
865
877
self .from_imports [reexport_imp ].update ((n , n ) for n in names )
866
878
879
+ if self .typing_extensions_min :
880
+ self .imports .add ("sys" )
867
881
for pkg in sorted (self .imports ):
868
882
self ._write_line (f"import { pkg } " )
883
+ if self .typing_extensions_min :
884
+ self ._write_line ("" )
885
+ self ._write_line (f"if sys.version_info >= { self .typing_extensions_min } :" )
886
+ self ._write_line (" import typing as typing_extensions" )
887
+ self ._write_line ("else:" )
888
+ self ._write_line (" import typing_extensions" )
869
889
870
890
for pkg , items in sorted (self .from_imports .items ()):
871
891
self ._write_line (f"from { pkg } import (" )
0 commit comments