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

Function refine_union

mypy/suggestions.py:1007–1037  ·  view source on GitHub ↗

Refine a union type based on another type. This is done by refining every component of the union against the right hand side type (or every component of its union if it is one). If an element of the union is successfully refined, we drop it from the union in favor of the refined ver

(t: UnionType, s: ProperType)

Source from the content-addressed store, hash-verified

1005
1006
1007def refine_union(t: UnionType, s: ProperType) -> Type:
1008 """Refine a union type based on another type.
1009
1010 This is done by refining every component of the union against the
1011 right hand side type (or every component of its union if it is
1012 one). If an element of the union is successfully refined, we drop it
1013 from the union in favor of the refined versions.
1014 """
1015 # Don't try to do any union refining if the types are already the
1016 # same. This prevents things like refining Optional[Any] against
1017 # itself and producing None.
1018 if t == s:
1019 return t
1020
1021 rhs_items = s.items if isinstance(s, UnionType) else [s]
1022
1023 new_items = []
1024 for lhs in t.items:
1025 refined = False
1026 for rhs in rhs_items:
1027 new = refine_type(lhs, rhs)
1028 if new != lhs:
1029 new_items.append(new)
1030 refined = True
1031 if not refined:
1032 new_items.append(lhs)
1033
1034 # Turn strict optional on when simplifying the union since we
1035 # don't want to drop Nones.
1036 with state.strict_optional_set(True):
1037 return make_simplified_union(new_items)
1038
1039
1040def refine_callable(t: CallableType, s: CallableType) -> CallableType:

Callers 1

refine_typeFunction · 0.85

Calls 5

make_simplified_unionFunction · 0.90
isinstanceFunction · 0.85
refine_typeFunction · 0.85
appendMethod · 0.80
strict_optional_setMethod · 0.80

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…