Narrowing causing Mypyc runtime type error
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.
@hauntsaninja could you please check this? @nickdrozd it will be helpful if you can give a full self-consistent repro.
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
- using a protocol Define Num as a Protocol. Mypyc treats Protocols with lenient structural checks that accept compatible types like
- Disable native compilation Use the @mypyc_attr(native_class=False) decorator to compile Num as a regular Python class:
This disables Mypyc's optimizations for Num but allows standard Python duck typing.
@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).
Will take a look! Could you share some setup / repro commands?
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.
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