Skip to content

[mypyc] Fix unchecked results of operations on overriding subclasses - #22416

Merged
JukkaL merged 1 commit into
python:masterfrom
Jahongir-Qurbonov:mypyc-subclass-result-type
Nov 10, 2026
Merged

JukkaL merged 1 commit into
python:masterfrom
Jahongir-Qurbonov:mypyc-subclass-result-type

Conversation

@Jahongir-Qurbonov

Copy link
Copy Markdown
Contributor

Several mypyc primitives declare an exact return type (str, list, tuple or dict), but they can end up calling a method that a Python subclass overrides. The result was then trusted without a type check, which can crash:

# sub.py (not compiled)
class L(list):
    def __add__(self, other):
        return 12345

# compiled
def f(a: list[int], b: list[int]) -> int:
    c = a + b
    return c[0]   # segfault when a is an L instance

The same problem affects:

  • list +=, *, n *, *= and .copy();
  • tuple +, * and n *;
  • dict.copy();
  • str * int. A heap str subclass that defines __mul__ has a NULL sq_repeat, so PySequence_Repeat falls through to the override;
  • str.lower() / str.upper() on non-ASCII strings on Python 3.13+.

Fix:

  • List, tuple and dict operations still call the override, as CPython does, but raise TypeError (e.g. "list object expected; got int") if the result has the wrong type. n * seq now calls __rmul__ instead of __mul__ on subclasses.
  • str * int and str.lower() / str.upper() always use the str implementation, so the result is an exact str. Other str primitives such as str + str (PyUnicode_Concat) already ignore subclass overrides, and this matches them.

Added run tests with overriding subclasses defined in a non-compiled module.

Several primitives declare an exact return type (str, list, tuple or
dict), but can call a method overridden in a Python subclass, and the
result was trusted without a type check. For example, if a list
subclass defines __add__ that returns an int, `c = a + b; c[0]` with
`a: list[int]` would crash.

For list and tuple +, +=, *, *= and list.copy(), and dict.copy(),
keep calling the override but raise TypeError if the result has the
wrong type. Also call __rmul__ instead of __mul__ for `n * seq` when
seq is a list or tuple subclass.

For str * int and str.lower()/str.upper() (non-ASCII, Python 3.13+),
always use the str implementation, so the result is an exact str. This
matches how other str primitives such as str + str already work.

@JukkaL JukkaL left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for the PR, looks good! It appears that some bytes primitives have a similar issue -- do you want to make a follow-up PR (e.g. CPyBytes_Multiply)?

@JukkaL
JukkaL merged commit 6349140 into python:master Nov 10, 2026
18 checks passed
@Jahongir-Qurbonov

Copy link
Copy Markdown
Contributor Author

Thanks! Opened #22431 for bytes * int, int * bytes, bytes.join() and bytes.translate(). It uses the same approach as for lists and tuples here.

@Jahongir-Qurbonov Jahongir-Qurbonov mentioned this pull request Nov 10, 2026
13 of 14 tasks
JukkaL pushed a commit that referenced this pull request Nov 11, 2026
…asses (#22431)

Follow-up to #22416, which fixed this for list, tuple, dict and str.

`bytes * int`, `int * bytes`, `bytes.join()`, `bytes.translate()` and
`bytes[i:j]` (with indices that don't fit in a short int) call the
overriding method when the object is a `bytes` subclass. The primitives
declare a `bytes` result, but the result was never checked, so an
override that returns another type was used as `bytes`:

```python
# sub.py (not compiled)
class B(bytes):
    def __mul__(self, n): return 42

# compiled
def f() -> None:
    b: bytes = B(b"x")
    r = b * 2
    print(len(r))  # interpreted: TypeError; compiled: prints garbage (reads an int as bytes)
```

Same approach as for lists and tuples in #22416: the override is still
called (the existing `testBytesJoin` test relies on this), but a
non-`bytes` result raises `TypeError`. `int * bytes` now calls
`__rmul__` on subclasses, not `__mul__`, matching CPython.
@Jahongir-Qurbonov
Jahongir-Qurbonov deleted the mypyc-subclass-result-type branch November 14, 2026 22:05
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.

2 participants