Skip to content

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

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

StrikeRougeAgent wants to merge 1 commit 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
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

1 participant