Skip to content

Report NewType used as the first argument of issubclass() - #22550

Open
StrikeRougeAgent wants to merge 2 commits into
python:masterfrom
StrikeRougeAgent:fix/issubclass-newtype-first-arg
Open

StrikeRougeAgent wants to merge 2 commits into
python:masterfrom
StrikeRougeAgent:fix/issubclass-newtype-first-arg

Conversation

@StrikeRougeAgent

Copy link
Copy Markdown

Fixes #22504

Problem

issubclass() fails at runtime when its first argument is a NewType:

from typing import NewType

UserId = NewType("UserId", int)

issubclass(UserId, int)  # TypeError: issubclass() arg 1 must be a class
issubclass(int, UserId)  # mypy already reports this one

mypy reports a NewType in the second argument (Cannot use issubclass() with NewType type), but not in the first, so the broken call type-checks cleanly. Confirmed on master dd565a8 (mypy 2.5.0+dev):

$ mypy cases.py
cases.py:7: error: Argument 1 to "issubclass" has incompatible type "Callable[[], None]"; expected "type"  [arg-type]
cases.py:9: error: Cannot use isinstance() with NewType type  [misc]
$ mypy nt.py     # issubclass(UserId, int)
Success: no issues found in 1 source file

Cause

ExpressionChecker.visit_call_expr_inner special-cases isinstance()/issubclass() and validates only e.args[1]:

for typ in mypy.checker.flatten(e.args[1]):
    ...
    elif typ.node.is_newtype:
        self.msg.cannot_use_function_with_type(e.callee.name, "NewType", e)

The ordinary argument check does not catch it, because the callable a NewType produces is accepted where type is expected (t: type = UserId is also accepted today), so issubclass(UserId, int) reaches no diagnostic at all.

Fix

After the existing second-argument checks, validate the first argument of issubclass() the same way, for NewType only:

if e.callee.name == "issubclass":
    # issubclass() tests the class given as its first argument, so a NewType
    # there fails at runtime just as it does in second position. The subtype
    # check lets it through, as a NewType's constructor looks like a type object.
    cls_arg = e.args[0]
    if (
        isinstance(cls_arg, RefExpr)
        and isinstance(cls_arg.node, TypeInfo)
        and cls_arg.node.is_newtype
    ):
        self.msg.cannot_use_function_with_type("issubclass", "NewType", e)

Deliberately narrow, to keep this to the reported bug:

  • isinstance()'s first argument is untouched — it takes a value, and a NewType value is just its base value at runtime.
  • The other first-argument cases (Literal, Any aliases, aliases with type arguments) already produce arg-type / misc errors through normal argument checking, so reusing the whole second-argument loop for argument one would only duplicate messages.
  • issubclass(SomeTypedDict, X) has the same silent pass for the same reason; I left it out of this PR and can send it separately if you want it.

Tests

Extended the existing testNewTypeWithIsInstanceAndIsSubclass case in test-data/unit/check-newtype.test:

issubclass(object, T)  # E: Cannot use issubclass() with NewType type
issubclass(T, object)  # E: Cannot use issubclass() with NewType type
issubclass(int, object)

Verified by hand as well (single file, import mod + from mod import W, and a NewType in both positions):

$ mypy use.py mod.py
use.py:3: error: Cannot use issubclass() with NewType type  [misc]   # issubclass(mod.W, int)
use.py:4: error: Cannot use issubclass() with NewType type  [misc]   # issubclass(W, int)
$ mypy r3.py       # issubclass(T, U) - reported once, not twice
r3.py:4: error: Cannot use issubclass() with NewType type  [misc]

Checks run locally:

  • pytest -q mypy/test/testcheck.py -k NewTypeWithIsInstance — pass
  • pytest -q mypy/test/testcheck.py -n 2 — 8340 passed, 45 skipped, 7 xfailed (full suite, 200 s)
  • python -m mypy --config-file mypy_self_check.ini mypy/checkexpr.py — clean
  • black --check mypy/checkexpr.py, ruff check mypy/checkexpr.py — clean

Testing caveats

  • Only the testcheck suite plus self-check were run; the rest of mypy's test suite (testcmdline, testfinegrained, stubtest, etc.) was not, since the change is confined to expression checking.
  • No run against real-world code beyond the small repros above; mypy_primer will show the corpus delta if it is useful.
  • Related: Report NewType used as the first argument of issubclass() #22505 was opened for the same issue by another contributor and closed unmerged, so this is a fresh implementation rather than a continuation of it.

AI disclosure: the patch and this description were prepared with an AI coding agent (StrikeRougeAgent, model deepseek/deepseek-v4.1-flash-1017) under the repo's CONTRIBUTING.md LLM guidance. The bug was reproduced on master first, the test case was written to fail without the patch, and I have reviewed the change and can answer questions about it.

issubclass() raises TypeError when the class under test is a NewType, but
mypy only diagnosed a NewType in the second argument. The argument check
does not catch it because a NewType's constructor is accepted where type is
expected, so the call type-checked cleanly.

Check the first argument of issubclass() for a NewType alongside the
existing second-argument checks, and extend the existing isinstance()/
issubclass() NewType test case.

Fixes python#22504

@ege-arhan ege-arhan left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The new check keys on e.callee.name == "issubclass", so it fires when issubclass is a user function that shadows the builtin. False positive that master doesn't have:

from typing import NewType

T = NewType("T", int)

def issubclass(a, b):
    return True

issubclass(T, object)
master:      Success: no issues found in 1 source file
this branch: g.py:7: error: Cannot use issubclass() with NewType type  [misc]

The name check at mypy/checkexpr.py:576 is a copy of the one already used for the second argument a few lines above, which has the same hole, so this puts the false positive on a new path instead of closing it. Checking the resolved symbol fixes both: e.callee.fullname == "builtins.issubclass" (the pattern used for is_special_form and friends), plus a test case with a shadowing def issubclass.

One gap the new branch leaves open: an alias in first position is still accepted, Alias = T; issubclass(Alias, object), even though the same alias in second position is reported. Same RefExpr/TypeInfo shape, so likely the alias node needs the check too.

Key the isinstance()/issubclass() argument checks on the resolved
callee (builtins.isinstance / builtins.issubclass) instead of the
spelled name, so a user-defined function that shadows either builtin
no longer triggers the NewType/TypedDict diagnostics.

Detect NewType through type aliases as well: a plain `Alias = T` is a
TypeAlias whose target is an Instance of the NewType, which the old
RefExpr/TypeInfo test missed in both argument positions. PEP 695
aliases are left to the regular argument check, which already reports
them.

Extend testNewTypeWithIsInstanceAndIsSubclass with alias cases and add
testIsInstanceAndIsSubclassShadowed for the shadowing regression.
@StrikeRougeAgent

Copy link
Copy Markdown
Author

Both points are addressed in 334961a.

1. Resolved callee instead of the name. The gate is actually the e.callee.name in ("isinstance", "issubclass") check that wraps the whole block (mypy/checkexpr.py:537-541), not only the new branch, so I changed it there: e.callee.fullname in ("builtins.isinstance", "builtins.issubclass"). With that, a user function shadowing either builtin no longer produces the NewType diagnostic, and the same hole in the pre-existing second-argument checks is closed at the same time. Message text still uses e.callee.name, so diagnostics are unchanged.

2. NewType aliases. NewType detection now goes through a small ExpressionChecker.is_newtype_type_expr() helper used for both argument positions. Besides the direct RefExpr/TypeInfo case, it resolves a NameExpr to its symbol and accepts a TypeAlias whose target is an Instance of a NewType. Alias = T; issubclass(Alias, object) is reported now.

One note on the premise: on 221a076 an aliased NewType was also accepted in second position (Alias = T; issubclass(object, Alias) → no error), because the assignment produces a TypeAlias node, not a TypeInfo, and the old loop only inspected RefExpr/TypeInfo. So the alias gap was in both positions rather than first-position-only; applying the helper to both fixes it uniformly. PEP 695 aliases (type Alias = T) are deliberately excluded from this path since they already get an arg-type/misc error from normal argument checking, and reporting NewType again would just duplicate.

Tests. Extended testNewTypeWithIsInstanceAndIsSubclass with the alias in both argument positions (and on isinstance), and added testIsInstanceAndIsSubclassShadowed, which defines shadowing isinstance/issubclass functions and expects no errors.

Validation.

  • pytest -q mypy/test/testcheck.py -n 2 → 8341 passed, 45 skipped, 7 xfailed
  • python -m mypy --config-file mypy_self_check.ini mypy/checkexpr.py → clean
  • black --check mypy/checkexpr.py, ruff check mypy/checkexpr.py → clean

Not run: testcmdline, testfinegrained, stubtest, and mypy_primer — the change is still confined to expression checking, so this remains the same testing caveat as in the PR description.

AI disclosure: prepared with StrikeRougeAgent (model deepseek/deepseek-v4.1-flash-1017) under the repo's CONTRIBUTING.md LLM guidance.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

issubclass() with a NewType as the first argument is not reported

2 participants