Skip to content

Fix cross-variable type-narrowing example #17488

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 6, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 10 additions & 6 deletions docs/source/type_narrowing.rst
Original file line number Diff line number Diff line change
Expand Up @@ -368,14 +368,18 @@ Limitations
Mypy's analysis is limited to individual symbols and it will not track
relationships between symbols. For example, in the following code
it's easy to deduce that if :code:`a` is None then :code:`b` must not be,
therefore :code:`a or b` will always be a string, but Mypy will not be able to tell that:
therefore :code:`a or b` will always be an instance of :code:`C`,
but Mypy will not be able to tell that:

.. code-block:: python

def f(a: str | None, b: str | None) -> str:
class C:
pass

def f(a: C | None, b: C | None) -> C:
if a is not None or b is not None:
return a or b # Incompatible return value type (got "str | None", expected "str")
return 'spam'
return a or b # Incompatible return value type (got "C | None", expected "C")
return C()

Tracking these sort of cross-variable conditions in a type checker would add significant complexity
and performance overhead.
Expand All @@ -385,9 +389,9 @@ or rewrite the function to be slightly more verbose:

.. code-block:: python

def f(a: str | None, b: str | None) -> str:
def f(a: C | None, b: C | None) -> C:
if a is not None:
return a
elif b is not None:
return b
return 'spam'
return C()