MCPcopy Create free account
hub / github.com/python/mypy / PolyTranslator

Class PolyTranslator

mypy/applytype.py:206–303  ·  view source on GitHub ↗

Make free type variables generic in the type if possible. See docstring for apply_poly() for details.

Source from the content-addressed store, hash-verified

204
205
206class PolyTranslator(TypeTranslator):
207 """Make free type variables generic in the type if possible.
208
209 See docstring for apply_poly() for details.
210 """
211
212 def __init__(
213 self,
214 poly_tvars: Iterable[TypeVarLikeType],
215 bound_tvars: frozenset[TypeVarLikeType] = frozenset(),
216 seen_aliases: frozenset[TypeInfo] = frozenset(),
217 ) -> None:
218 super().__init__()
219 self.poly_tvars = set(poly_tvars)
220 # This is a simplified version of TypeVarScope used during semantic analysis.
221 self.bound_tvars = bound_tvars
222 self.seen_aliases = seen_aliases
223
224 def collect_vars(self, t: CallableType | Parameters) -> list[TypeVarLikeType]:
225 found_vars = []
226 for arg in t.arg_types:
227 for tv in get_all_type_vars(arg):
228 if isinstance(tv, ParamSpecType):
229 normalized: TypeVarLikeType = tv.copy_modified(
230 flavor=ParamSpecFlavor.BARE, prefix=Parameters([], [], [])
231 )
232 else:
233 normalized = tv
234 if normalized in self.poly_tvars and normalized not in self.bound_tvars:
235 found_vars.append(normalized)
236 return remove_dups(found_vars)
237
238 def visit_callable_type(self, t: CallableType) -> Type:
239 found_vars = self.collect_vars(t)
240 self.bound_tvars |= set(found_vars)
241 result = super().visit_callable_type(t)
242 self.bound_tvars -= set(found_vars)
243
244 assert isinstance(result, ProperType) and isinstance(result, CallableType)
245 result.variables = result.variables + tuple(found_vars)
246 return result
247
248 def visit_type_var(self, t: TypeVarType) -> Type:
249 if t in self.poly_tvars and t not in self.bound_tvars:
250 raise PolyTranslationError()
251 return super().visit_type_var(t)
252
253 def visit_param_spec(self, t: ParamSpecType) -> Type:
254 if t in self.poly_tvars and t not in self.bound_tvars:
255 raise PolyTranslationError()
256 return super().visit_param_spec(t)
257
258 def visit_type_var_tuple(self, t: TypeVarTupleType) -> Type:
259 if t in self.poly_tvars and t not in self.bound_tvars:
260 raise PolyTranslationError()
261 return super().visit_type_var_tuple(t)
262
263 def visit_type_alias_type(self, t: TypeAliasType) -> Type:

Callers 2

apply_polyFunction · 0.85
visit_instanceMethod · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…