Skip to content
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

document ternary/conditional type inference limitations #6649

Closed
wants to merge 2 commits into from
Closed
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: 16 additions & 0 deletions docs/source/common_issues.rst
Original file line number Diff line number Diff line change
Expand Up @@ -339,6 +339,22 @@ style anyway). We can write the above code without a cast by using
g(o + 1) # Okay; type of o is inferred as int here
...

Note that Mypy cannot always narrow a type based on ``isinstance()``
used within a ternary/conditional expression, e.g.:

.. code-block:: python

def f(x: AnyStr) -> bytes:
r = x.encode('ascii') if isinstance(x, str) else x
# results in 'error: "bytes" has no attribute "encode"; maybe "decode"?'

if isinstance(x, str):
r = x.encode('ascii') # whereas Mypy can narrow within an if statement
else:
r = x
return r
...

Type inference in mypy is designed to work well in common cases, to be
predictable and to let the type checker give useful error
messages. More powerful type inference strategies often have complex
Expand Down