mypy icon indicating copy to clipboard operation
mypy copied to clipboard

Narrowing causing Mypyc runtime type error

Open nickdrozd opened this issue 9 months ago • 6 comments

Have code that uses type alias ubiquitously:

type Count = int | Num

where Num is int-like. Num and int interact and coexist. Has been running fine compiled with Mypyc.

https://github.com/python/mypy/commit/e64a84b118bb338ec6efd428d398e6ebd5b79bfc has introduced some problem. Now getting TypeError: tm.num.Num object expected; got int.

nickdrozd avatar Feb 05 '26 14:02 nickdrozd

@hauntsaninja could you please check this? @nickdrozd it will be helpful if you can give a full self-consistent repro.

ilevkivskyi avatar Feb 05 '26 14:02 ilevkivskyi

Now getting TypeError: tm.num.Num object expected; got int.

Root cause analysis The TypeError: tm.num.Num object expected; got int occurs because Mypyc compiles the Num class as a strict native class, which enforces nominal type checking at runtime using PyObject_TypeCheck. This check only accepts instances that are exactly of type Num or its subclasses, rejecting int even if it's logically compatible.

We can solve this issue in two ways

  1. using a protocol Define Num as a Protocol. Mypyc treats Protocols with lenient structural checks that accept compatible types like
Image
  1. Disable native compilation Use the @mypyc_attr(native_class=False) decorator to compile Num as a regular Python class:
Image

This disables Mypyc's optimizations for Num but allows standard Python duck typing.

alansajith avatar Feb 05 '26 16:02 alansajith

@ilevkivskyi I don't have a small reproducer. Here is affected module: https://github.com/nickdrozd/busy-beaver-stuff/blob/main/tm/num.py. Runs fine with previous commit (eabda0eef).

nickdrozd avatar Feb 05 '26 16:02 nickdrozd

Will take a look! Could you share some setup / repro commands?

hauntsaninja avatar Feb 05 '26 20:02 hauntsaninja

test_num.py num.py

With these two files, run python3 -m mypyc num.py && python3 -m unittest test_num. Should get a bunch of test failures with message TypeError: num.Num object expected; got int.

nickdrozd avatar Feb 05 '26 21:02 nickdrozd

Thank you!

Codex minimised the test case a little:

from __future__ import annotations


type Count = int | Num


class Num:
    def __eq__(self, other: object) -> bool:
        return other is self

    def __radd__(self, other: int) -> Count:
        raise NotImplementedError


class Exp(Num):
    exp: Count

    def __init__(self, exp: Count) -> None:
        self.exp = exp

    def __add__(self, other: Count) -> Count:
        if isinstance(other, Exp):
            sexp, oexp = self.exp, other.exp

            if sexp == oexp:
                return Exp(1 + sexp)

        return self


def run() -> Count:
    return Exp(3) + Exp(3)

I see what logic I'm missing (comparison between custom eq expr and custom eq target), will put up a PR soon

hauntsaninja avatar Feb 05 '26 22:02 hauntsaninja