Skip to content

Assorted CPython compatibility divergences (18 items) #9913

Open

Description

@jseop-lim

Feature

Found by differential testing against CPython 3.12. All 18 items reproduce on main at 7abccf0 (the outputs below are from that build), and CPython 3.12.13, 3.14.4 and 3.15.2 agree on each, apart from the wording of one message noted in item 13. Every item has a reproduction, both outputs and the cause, with a suggested fix folded underneath.

I have a fix for each item and will open the PRs as they are ready. Anyone is welcome to pick up any item and open a PR for it.

  • 1. _thread.stack_size(2**64): ValueError on RustPython, OverflowError on CPython
  • 2. pow(1+2j, "x", 3): ValueError on RustPython, TypeError on CPython
  • 3. format("x", "\u0665"): ValueError on RustPython, 'x ' on CPython
  • 4. struct.pack("d", "a"): TypeError on RustPython, struct.error on CPython
  • 5. struct.pack_into("Z", bytearray(4), 10**100): OverflowError on RustPython, struct.error on CPython
  • 6. io.FileIO(fd, "r", None), os.set_blocking(fd, None): TypeError on RustPython, accepted on CPython
  • 7. _codecs.utf_8_decode(b"", "strict", None), binascii.a2b_qp(b"a_b", None): TypeError on RustPython, accepted on CPython
  • 8. marshal.dumps([FloatSubclass(0.5)]): bytes on RustPython, ValueError on CPython
  • 9. bytes("x", "utf-8\0"): b'x' on RustPython, ValueError on CPython
  • 10. bytes(L([1, 2, 3])) with L.__iter__ overridden: stored items on RustPython, iterated items on CPython
  • 11. csv.register_dialect(BadHash("x")): accepted on RustPython, the __hash__ exception on CPython
  • 12. type(iter("abc")): str_iterator on RustPython, str_ascii_iterator on CPython
  • 13. collections._count_elements(None, IterReturnsInt()): AttributeError on RustPython, TypeError on CPython
  • 14. operator.concat(UserString("a"), 1): 'a1' on RustPython, TypeError on CPython
  • 15. getattr(K(), BadHash("x"), 0): 0 on RustPython, the __hash__ exception on CPython
  • 16. sorted([1, 2, 3], reverse=None): TypeError on RustPython, [1, 2, 3] on CPython
  • 17. Interpreter shutdown imports threading on RustPython, not on CPython
  • 18. compile("if x:\n a\n ", "<foo>", "single"): a code object on RustPython, SyntaxError on CPython

1. _thread.stack_size() reports an out-of-range size as ValueError, or accepts it

Expression RustPython CPython
_thread.stack_size(2**64) ValueError: size must be at least 53248 bytes OverflowError: Python int too large to convert to C ssize_t
_thread.stack_size(-10**100) ValueError: size must be at least 53248 bytes OverflowError: Python int too large to convert to C ssize_t
_thread.stack_size(2**63) 0 OverflowError: Python int too large to convert to C ssize_t

stack_size (_thread.rs#L927-L940) converts its argument to usize and reports a failed conversion as the minimum-size ValueError, so 2**63 to 2**64 - 1 is accepted. CPython's thread_stack_size parses the size as Py_ssize_t first (_threadmodule.c#L2204-L2212).

Fix suggestion

In stack_size, convert the size to isize, raising OverflowError when it does not fit, and compare the signed value with the minimum size.

2. Three-argument pow() with a complex raises complex modulo before looking at the operands

Expression RustPython CPython
pow(1+2j, "x", 3) ValueError: complex modulo TypeError: unsupported operand type(s) for ** or pow(): 'complex', 'str', 'int'
pow("x", 1+2j, 3) ValueError: complex modulo TypeError: unsupported operand type(s) for ** or pow(): 'str', 'complex', 'int'

complex's power slot (complex.rs#L770-L776) raises as soon as a modulus is given. CPython's complex_pow converts both operands first and returns NotImplemented for one that is not a number (complexobject.c#L740-L750).

Fix suggestion

Route the power slot through PyComplex::number_op with or without a modulus, and raise complex modulo only once both operands are converted.

3. A format spec width or precision accepts only ASCII digits

Expression RustPython CPython
format("x", "\u0665") ValueError: Unknown format code '٥' for object of type 'str' 'x '
format(3, "\u0665d") ValueError: Invalid format specifier '٥d' for object of type 'int' ' 3'
format(1.5, "\u0668.\u0663f") ValueError: Invalid format specifier '٨.٣f' for object of type 'float' ' 1.500'

The parser reads the number with get_num_digits (format.rs#L217-L224), which stops at the first character that is not an ASCII digit. CPython's get_integer converts each character with Py_UNICODE_TODECIMAL, so any Unicode decimal digit counts (unicode_formatter.c#L296-L326).

Fix suggestion

Read the number one character at a time in parse_number, testing an ASCII character directly and a non-ASCII one with char_to_decimal, and keep the overflow check.

4. struct.pack() lets a float conversion error through

class RaisingFloat:
    def __float__(self):
        raise RuntimeError
Expression RustPython CPython
struct.pack("d", "a") TypeError: must be real number, not str struct.error: required argument is not a float
struct.pack("<f", None) TypeError: must be real number, not NoneType struct.error: required argument is not a float
struct.pack("e", RaisingFloat()) RuntimeError struct.error: required argument is not a float

The f and d packers (buffer.rs#L694-L724) and the e packer (#L841-L854) propagate the argument's conversion error. CPython's float packers replace any conversion failure with struct.error (_struct.c#L776-L786, #L276-L288).

Fix suggestion

In the e, f and d packers, map a failed ArgIntoFloat conversion to struct.error, as the complex packers already do.

5. A bad struct format is reported after the other arguments are converted

Expression RustPython CPython
struct.pack_into("Z", bytearray(4), 10**100) OverflowError: Python int too large to convert to Rust isize struct.error: bad char in struct format
struct.unpack_from("Z", b"", 10**100) OverflowError: Python int too large to convert to Rust isize struct.error: bad char in struct format
struct.unpack("Z", 5) TypeError: a bytes-like object is required, not 'int' struct.error: bad char in struct format

The module-level functions, such as pack_into (pystruct.rs#L133-L144), bind every argument and parse the format in the body. CPython runs cache_struct_converter on the format before it converts the arguments after it (_struct.c.h#L518-L536).

Fix suggestion

Bind the format of pack, pack_into, unpack, unpack_from, iter_unpack and calcsize as an argument type that parses it through the cache during binding.

6. Flag arguments in io and os accept only int instances

fd below is any open file descriptor.

Expression RustPython CPython
io.IncrementalNewlineDecoder(None, None) TypeError: Expected type bool, not NoneType <_io.IncrementalNewlineDecoder object at 0x...>
io.IncrementalNewlineDecoder(None, True).decode("a\r", None) TypeError: Expected type bool, not NoneType 'a'
io.FileIO(fd, "r", None) TypeError: Expected type bool, not NoneType <_io.FileIO name=3 mode='rb' closefd=False>
os.set_blocking(fd, None) TypeError: Expected type bool, not NoneType None
os.dup2(fd, 77, None) TypeError: Expected type bool, not NoneType 77

translate, final, closefd, blocking and inheritable are bound as a Rust bool, whose conversion accepts only int instances (bool.rs#L19-L32). CPython declares all five as Argument Clinic bool, which calls PyObject_IsTrue (for example fileio.c.h#L127), so any object is accepted and an exception from __bool__ propagates.

Fix suggestion

Bind the five flags as ArgIntoBool in crates/vm/src/stdlib/_io.rs and crates/vm/src/stdlib/posix.rs. The Windows versions in nt.rs, the positional target_is_directory of os.symlink, the closefd of open() and the keyword-only flags in os (follow_symlinks, effective_ids) have the same conversion.

7. Flag arguments in _codecs and binascii accept only int instances

Expression RustPython CPython
_codecs.utf_8_decode(b"", "strict", None) TypeError: Expected type bool, not NoneType ('', 0)
binascii.a2b_qp(b"a_b", None) TypeError: Expected type bool, not NoneType b'a_b'
binascii.b2a_qp(b"a b", False, True, "x") TypeError: Expected type bool, not str b'a_b'

The final argument of the decoders (_codecs.rs#L188-L196) and the flags of a2b_qp(), b2a_qp() and b2a_uu() (binascii.rs#L628-L676) are bound as a Rust bool, as in item 6. CPython converts each with PyObject_IsTrue (_codecsmodule.c.h#L517-L523, binascii.c.h#L1655-L1676).

Fix suggestion

Bind final as ArgIntoBool in DecodeArgs, EscapeTextDecodeArgs and ExDecodeArgs, and header, quotetabs, istext and backtick in binascii.rs, as the other flags in that module already are. The Windows-only decoders (mbcs, oem, code_page) have the same conversion.

8. marshal.dumps() writes a nested subclass instance as its base type

class FloatSubclass(float):
    pass
Expression RustPython CPython
marshal.dumps([FloatSubclass(0.5)]) b'[\x01\x00\x00\x00g\x00\x00\x00\x00\x00\x00\xe0?' ValueError: unmarshallable object

dumps runs check_exact_type (marshal.rs#L982-L1003) only on the top-level value (#L120). Inside a container, write_object_depth picks the wire type with downcast_ref, which also matches subclasses. CPython's w_complex_object tests every object with PyFloat_CheckExact and the like, at any depth.

Fix suggestion

Move the check_exact_type call from dumps into write_object_depth, so it runs on every object written.

9. A null character in encoding, errors or compile()'s mode goes unnoticed

Expression RustPython CPython
bytes("x", "utf-8\0") b'x' ValueError: embedded null character
bytearray("x", "utf-8", "strict\0") bytearray(b'x') ValueError: embedded null character
str(b"x", "utf-8", "strict\0") 'x' ValueError: embedded null character
compile("x", "f", "ex\0ec", {}) TypeError: 'dict' object cannot be interpreted as an integer ValueError: embedded null character

bytes() and bytearray() bind encoding and errors as plain strings (bytes_inner.rs#L169-L177), str() only checks that they are str (str.rs#L400-L416), and compile() does the same for mode (builtins.rs#L117-L123). CPython converts each to a C string while parsing the arguments and raises there (bytesobject.c.h#L1426-L1451, bytearrayobject.c.h#L75-L100, unicodeobject.c.h#L1887-L1912, bltinmodule.c.h#L411-L426).

Fix suggestion

Bind those arguments as a str argument type whose conversion raises ValueError for a null character, so the check runs in argument order. compile()'s filename then has to be converted during binding too, to stay ahead of mode. str.encode(), bytes.decode() and bytearray.decode() accept a null character in the same two arguments.

10. bytes() and bytearray() read a list or tuple subclass's stored items

class L(list):
    def __iter__(self):
        return iter([65, 66])
Expression RustPython CPython
bytes(L([1, 2, 3])) b'\x01\x02\x03' b'AB'
bytearray(L([1, 2, 3])) bytearray(b'\x01\x02\x03') bytearray(b'AB')

map_iterable_object_inner (vm/mod.rs#L3735-L3762) has PyList and PyTuple arms that also match subclasses, so an overridden __iter__ is never called. CPython's bytes() takes that shortcut only for an exact list or tuple (bytesobject.c#L3142-L3146), and bytearray() always iterates (bytearrayobject.c#L1129-L1131).

Fix suggestion

In map_iterable_object_inner, iterate anything that is not an exact list or tuple before reaching the arms that read the items directly.

11. The csv dialect registry does not hash a str subclass name

class BadHash(str):
    def __hash__(self):
        raise ValueError
Expression RustPython CPython
csv.register_dialect(BadHash("x")) None ValueError
csv.get_dialect(BadHash("excel")) <_csv.Dialect object at 0x...> ValueError
csv.unregister_dialect(BadHash("excel")) None ValueError

register_dialect, get_dialect and unregister_dialect (csv.rs#L197-L244) key the registry on the text of a str name and hash only a name that is not a str (#9514). CPython keeps the registry in a dict and passes the name object to it, which calls its __hash__ (_csv.c#L1635-L1638, #L162-L170, #L1652-L1666).

Fix suggestion

Have registry_key() hash every name before checking that it is a str, and hash the name in register_dialect() once the dialect is validated, where CPython inserts it.

12. An ASCII str has no str_ascii_iterator

Expression RustPython CPython
type(iter("abc")).__name__ 'str_iterator' 'str_ascii_iterator'
type(iter("abc")) is type(iter("\xe9")) True False

PyStr::iter (str.rs#L1737-L1751) always builds a str_iterator. CPython's unicode_iter gives an exact str holding only ASCII the separate str_ascii_iterator type (unicodeobject.c#L14784-L14797).

Fix suggestion

Add a str_ascii_iterator type with the methods str_iterator has, and return it from PyStr::iter for an exact str whose kind is ASCII.

13. An __iter__ that returns a non-iterator is rejected only on the first next()

class IterReturnsInt:
    def __iter__(self):
        return 1
Expression RustPython CPython
collections._count_elements(None, IterReturnsInt()) AttributeError: 'NoneType' object has no attribute 'get' TypeError: IterReturnsInt.__iter__() must return an iterator, not int

CPython 3.12 and 3.14 word the message iter() returned non-iterator of type 'int'.

ArgIterable::get_iter (protocol.rs#L99-L104) wraps whatever __iter__ returns, and _count_elements (_collections.rs#L1494-L1523) reads mapping.get before the first next(). CPython's PyObject_GetIter checks the result before returning it (abstract.c#L2825-L2831).

Fix suggestion

In ArgIterable::get_iter, get the iterator through PyIter::try_from_object, which already rejects a non-iterator result.

14. operator.concat() and operator.iconcat() check only the first operand's __getitem__

class ListWithIadd(list):
    def __iadd__(self, other):
        return "iadded"
Expression RustPython CPython
operator.concat(collections.UserString("a"), 1) 'a1' TypeError: 'UserString' object can't be concatenated
operator.iconcat(collections.UserList([1]), {2}) [1, 2] TypeError: 'UserList' object can't be concatenated
operator.iconcat(ListWithIadd([1]), [2]) 'iadded' [1, 2]

concat (_operator.rs#L163-L173) and iconcat (#L252-L263) check that the first operand has __getitem__, then evaluate a + b or a += b. CPython's PySequence_Concat and PySequence_InPlaceConcat use the sequence slots of the first operand and fall back to the number slots only when both operands are sequences (abstract.c#L1721-L1744, #L1778-L1804).

Fix suggestion

Call PySequence::concat and PySequence::inplace_concat, keeping the up-front rejection of a dict subclass. A class that defines __iadd__ in Python must then stop inheriting the native sq_inplace_concat in crates/vm/src/types/slot.rs, as a Python __add__ already drops sq_concat, or iconcat would extend such a list subclass in place.

15. Attribute lookup does not hash a str subclass name

class BadHash(str):
    def __hash__(self):
        raise ValueError

class K:
    pass
Expression RustPython CPython
getattr(K(), BadHash("x"), 0) 0 ValueError
hasattr(K(), BadHash("x")) False ValueError
setattr(K(), BadHash("x"), 0) None ValueError

generic_getattr_opt (object.rs#L282-L290) and generic_setattr (#L234-L238) look the name up in the instance __dict__ as a Py<PyStr> key, which hashes the string data. CPython's _PyObject_GenericGetAttrWithDict passes the name object to PyDict_GetItemRef, which hashes it with PyObject_Hash (object.c#L1935-L1967).

Fix suggestion

Use the name object as the __dict__ key when it is not an exact str. CPython creates a function's or a builtin instance's __dict__ lazily and skips the lookup while there is none, so getattr(lambda: 0, BadHash("x"), 0) returns 0 there, and the lookup has to skip an empty __dict__ on such objects to keep that.

16. sorted() and list.sort() accept only an int instance as reverse

Expression RustPython CPython
sorted([1, 2, 3], reverse=None) TypeError: Expected type bool, not NoneType [1, 2, 3]
sorted([1, 2, 3], reverse="x") TypeError: Expected type bool, not str [3, 2, 1]

SortOptions (list.rs#L183-L190) binds reverse as a Rust bool, as in item 6. CPython converts it with PyObject_IsTrue (listobject.c.h#L267-L270).

Fix suggestion

Bind reverse as an object and convert it by truth value inside PyList::sort. Converting it during binding would call __bool__ before sorted() reads its iterable, and CPython reads the iterable first.

17. Interpreter shutdown imports threading

Command RustPython CPython
-c "import atexit, sys; atexit.register(lambda: print('threading' in sys.modules))" True False
-c "import sys; sys.settrace(print)" 408 lines of frames from importlib._bootstrap and threading no output

finalize_ex (interpreter.rs#L820-L833) imports threading to call _shutdown(), so a program that never imported it runs the import machinery on exit, with a trace function still installed. CPython's wait_for_thread_shutdown looks the module up with PyImport_GetModule and returns when it was never imported (pylifecycle.c#L3843-L3853).

Fix suggestion

In finalize_ex, take threading from sys.modules and skip _shutdown() when it is absent.

18. compile(..., 'single') accepts a compound statement followed by an unterminated blank line

Expression RustPython CPython
compile("if x:\n a\n ", "<foo>", "single") <code object <module> at 0x..., file "<foo>", line 1> SyntaxError: invalid syntax
compile("if x:\n a\n ", "<foo>", "single") a code object IndentationError: unindent does not match any outer indentation level
compile("if x:\n a\n#c", "<foo>", "single") a code object SyntaxError: invalid syntax

With a newline after the last line ("if x:\n a\n \n") both accept the source.

'single' input is parsed as a module (lib.rs#L2157-L2163), where a trailing whitespace-only or comment-only line is blank whether or not a newline ends it, and the single-mode checks (#L1903-L1973, #L1248-L1268) do not look at it. CPython adds a final newline only to exec input (helpers.c#L313-L318), so in single mode the tokenizer reaches the end of input inside that line, and the parser turns ENDMARKER into a NEWLINE while the block is still open (pegen.c#L270-L278), which single_compound_stmt NEWLINE cannot match.

Fix suggestion

Add a single-mode check for a compound first statement whose source does not end in a line break and whose last line is only indentation or a comment, comparing that line's indentation with the open blocks to pick invalid syntax, unindent does not match any outer indentation level, unexpected indent or TabError.

Python Documentation or reference to CPython source code

The CPython source for each item is linked in the item above (CPython v3.15.2).

AI disclosure: this report was drafted with Claude Code (claude-fable-5-2) and reviewed by me before submission. The divergences come from differential-testing runs against CPython 3.12.13, and every source reference was checked against the linked revisions.

Activity

  1. added
    C-compat
    on Nov 17, 2026
  2. youknowone commented on Nov 18, 2026

    @youknowone
    Member

    Awesome, thanks!

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-compat

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions