I have a variable of type list[A | B] that could hold a mixed list (like [A(), B(), A()]).
If I later reach some corner case and I want to make sure all elements are actually of type A, I can assert isinstance inside a for-loop:
def f(mylist: list[A | B]):
...
...
for el in mylist:
assert isinstance(el, A)
# Now, I'm sure that mylist is actually `list[A]`
# How do I tell that to the type checker?
After the for-loop, if I reveal_type(mylist) it still says list[A|B]. I also tried assert all(isinstance(el, A) for el in mylist) instead of the explicit loop, but mypy still isn't able to narrow it. Is this possible? Or do I have to use cast here?