Skip to content

Docs: adds a note about issubclass usage in common_issues.rst #11014

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 3 commits into from
Sep 4, 2021
Merged
Changes from 1 commit
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
20 changes: 18 additions & 2 deletions docs/source/common_issues.rst
Original file line number Diff line number Diff line change
Expand Up @@ -392,7 +392,7 @@ explicit type cast:

Mypy can't infer the type of ``o`` after the :py:class:`type() <type>` check
because it only knows about :py:func:`isinstance` (and the latter is better
style anyway). We can write the above code without a cast by using
style anyway). We can write the above code without a cast by using
:py:func:`isinstance`:

.. code-block:: python
Expand All @@ -402,7 +402,23 @@ 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
...

Type inference in mypy is designed to work well in common cases, to be
Mypy can also use :py:func:`issubclass`
for better type inference when working with types:

.. code-block:: python

class MyCalcMeta(type):
@classmethod
def calc(cls) -> int:
...

def f(o: object) -> None:
t = type(o) # we must use a variable here
if issubtype(t, MyCalcMeta): # `issubtype(type(o), MyCalcMeta)` won't work
reveal_type(t) # Revealed type is "Type[MyCalcMeta]"
t.calc() # Okay

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
and difficult-to-predict failure modes and could result in very
Expand Down