MCPcopy
hub / github.com/python/mypy / calculate_tuple_fallback

Function calculate_tuple_fallback

mypy/semanal_shared.py:278–312  ·  view source on GitHub ↗

Calculate a precise item type for the fallback of a tuple type. This must be called only after the main semantic analysis pass, since joins aren't available before that. Note that there is an apparent chicken and egg problem with respect to verifying type arguments against bounds.

(typ: TupleType)

Source from the content-addressed store, hash-verified

276
277
278def calculate_tuple_fallback(typ: TupleType) -> None:
279 """Calculate a precise item type for the fallback of a tuple type.
280
281 This must be called only after the main semantic analysis pass, since joins
282 aren't available before that.
283
284 Note that there is an apparent chicken and egg problem with respect
285 to verifying type arguments against bounds. Verifying bounds might
286 require fallbacks, but we might use the bounds to calculate the
287 fallbacks. In practice this is not a problem, since the worst that
288 can happen is that we have invalid type argument values, and these
289 can happen in later stages as well (they will generate errors, but
290 we don't prevent their existence).
291 """
292 fallback = typ.partial_fallback
293 assert fallback.type.fullname == "builtins.tuple"
294 items = []
295 for item in flatten_nested_tuples(typ.items):
296 # TODO: this duplicates some logic in typeops.tuple_fallback().
297 if isinstance(item, UnpackType):
298 unpacked_type = get_proper_type(item.type)
299 if isinstance(unpacked_type, TypeVarTupleType):
300 unpacked_type = get_proper_type(unpacked_type.upper_bound)
301 if (
302 isinstance(unpacked_type, Instance)
303 and unpacked_type.type.fullname == "builtins.tuple"
304 ):
305 items.append(unpacked_type.args[0])
306 else:
307 # This is called before semanal_typeargs.py fixes broken unpacks,
308 # where the error should also be generated.
309 items.append(AnyType(TypeOfAny.from_error))
310 else:
311 items.append(item)
312 fallback.args = (make_simplified_union(items),)
313
314
315class _NamedTypeCallback(Protocol):

Callers 2

Calls 6

flatten_nested_tuplesFunction · 0.90
get_proper_typeFunction · 0.90
AnyTypeClass · 0.90
make_simplified_unionFunction · 0.90
isinstanceFunction · 0.85
appendMethod · 0.80

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…