[Bug]: Assorted CPython compatibility divergences (21 items)

未关闭
#1,360 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

维护者通常 1 天内回复

还没有人认领这个 Issue。

评估

难度
3/5
预计耗时
1-2 天
新手友好度
55/100
Issue 类型
缺陷
描述清晰度
基本清楚
活跃度
活跃
技术栈
java, python
领域
backend, compilers

调研方向

This is a tracking issue with 21 independent items; pick one and work only that item. For item 1, start in BytesNodes.java (ExpectStringNode, around lines 481-521) and StringBuiltins.java (checkEncodingAndErrors, around lines 380-387), and reproduce with bytes([], 'utf-8\x00') on a GraalPy build. Done means the call raises ValueError with the embedded null character message, matching CPython 3.12 for each row in the table.

由索引模型根据 Issue 内容生成。

描述

bug
Describe the bug

Found by differential testing against CPython 3.12. All 21 items reproduce on master at 3289197e63, and CPython 3.12.13 and 3.13.14 give the same expected output for each unless an item says otherwise. Every item under "Steps to reproduce" 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 in small batches. Anyone is welcome to pick up any item and open a PR for it.

  • 1. bytes([], 'utf-8\x00'), str(b'x', 'utf-8\x00'): TypeError or accepted on GraalPy, ValueError on CPython
  • 2. compile('1', RaisingPath(), 0), compile('1', 'f', 'ex\x00ec', {}), compile('1', 'f', 'eval', 0, []): TypeError on GraalPy, the __fspath__ error, ValueError, a code object on CPython
  • 3. complex(Good(1), 2j) with Good.__complex__: (-1+0j) on GraalPy, (3+0j) on CPython
  • 4. sum(x, '') where iter(x) raises: TypeError for start on GraalPy, the iter() error on CPython
  • 5. list(x) where x has only a raising __len__: the __len__ error on GraalPy, TypeError on CPython
  • 6. getattr(super(int, 1), name, None) with a str subclass name whose __hash__ raises: None on GraalPy, the __hash__ error on CPython
  • 7. csv.register_dialect(name) with a str subclass name whose __hash__ raises: None on GraalPy, the __hash__ error on CPython
  • 8. metaclass mro() that leaves out the new class: class created on GraalPy, TypeError on CPython
  • 9. type('C', (B, int), {}) where B has a custom MRO without object: TypeError on GraalPy, class created on CPython
  • 10. class whose metaclass drops __classcell__: created on GraalPy, RuntimeError on CPython
  • 11. UnicodeDecodeError('ascii', 'bytes', 0, 1, 'ouch'): accepted on GraalPy, TypeError on CPython
  • 12. str() of a bytes subclass that overrides __repr__: the override on GraalPy, b'...' on CPython
  • 13. type(weakref.proxy(C)) for a callable C: ProxyType on GraalPy, CallableProxyType on CPython
  • 14. coro().__name__, agen().__qualname__: AttributeError on GraalPy, the name on CPython
  • 15. types.FunctionType(func.__code__, {}).__name__: <lambda> on GraalPy, func on CPython
  • 16. copy.deepcopy(x) with a __getattr__ that answers unknown names: TypeError on GraalPy, a copy on CPython
  • 17. ast.unparse(list): '' on GraalPy, AttributeError on CPython
  • 18. heapq.heappushpop(None, 1), heapq.heapify(()): 1, None on GraalPy, TypeError on CPython
  • 19. itertools.combinations(it, 1) with a negative __length_hint__: never returns on GraalPy, ValueError on CPython
  • 20. itertools.tee([], -2**32 - 1), batched([], -2**32 - 1): OverflowError on GraalPy, ValueError on CPython
  • 21. __loader__ in graalpy script.py: None on GraalPy, a SourceFileLoader on CPython
Operating system

macOS

CPU architecture

ARM64

GraalPy version

master 3289197e63 (Python 3.13.14), built with mx python-jvm

JDK version

No response

Context configuration

No response

Steps to reproduce
1. str(), bytes() and bytearray() accept an embedded null in encoding and errors
Expression GraalPy CPython
bytes([], 'utf-8\x00') TypeError: errors without a string argument ValueError: embedded null character
bytes('x', 'utf-8\x00') LookupError: unknown encoding utf-8\x00 ValueError: embedded null character
bytes('x', 'utf-8', 'strict\x00') b'x' ValueError: embedded null character
bytearray([], 'utf-8\x00') TypeError: errors without a string argument ValueError: embedded null character
str('x', 'utf-8\x00') TypeError: decoding to str: need a bytes-like object, str found ValueError: embedded null character
str(b'x', 'utf-8\x00') 'x' ValueError: embedded null character

bytes() and bytearray() convert both arguments with BytesNodes.ExpectStringNode (BytesNodes.java#L481-L521), and str() checks them in checkEncodingAndErrors (StringBuiltins.java#L380-L387). Both only test that the value is a str, so a null character reaches the later argument checks, the codec lookup, or is never looked at. CPython's argument clinic rejects it while converting the argument (bytesobject.c.h#L1036-L1042, bytearrayobject.c.h#L72-L78, unicodeobject.c.h#L1471-L1477), before anything else is checked.

Fix suggestion

In ExpectStringNode and in checkEncodingAndErrors, raise ValueError with ErrorMessages.EMBEDDED_NULL_CHARACTER when the string contains U+0000, right after the str check of that argument.

2. compile() converts filename last, accepts a null in mode and requires an integer dont_inherit
class RaisingPath:
    def __fspath__(self):
        raise KeyError('fspath')
Expression GraalPy CPython
compile('1', RaisingPath(), 0) TypeError: compile() argument must be str, not int KeyError: 'fspath'
compile('1', 'a\x00', 'eval') <code object <module>, file "a\x00", line 1> ValueError: embedded null character
compile('1', 'f', 'ex\x00ec', {}) TypeError: 'dict' object cannot be interpreted as an integer ValueError: embedded null character
compile('1', 'f', 'eval', 0, []) TypeError: 'list' object cannot be interpreted as an integer <code object <module> at 0x..., file "f", line 1>

Three conversions in CompileNode's argument clinic (BuiltinFunctions.java#L928-L933) differ from CPython's (bltinmodule.c.h#L327-L361):

  • filename is not converted by the clinic. The generic specialization decodes it after the other arguments, and doCompile, which takes a str source with a str filename, never checks it. CPython calls PyUnicode_FSDecoder on it first.
  • mode uses ClinicConversion.TString, which lets a null character through; the unknown mode is only reported in the body, after flags and optimize are converted. CPython rejects the null while converting mode.
  • dont_inherit uses ClinicConversion.IntToBoolean, the counterpart of bool(accept={int}). CPython declares it bool and calls PyObject_IsTrue.
Fix suggestion

In the clinic declaration, give filename a converter that calls PyUnicodeFSDecoderNode (and drop the call in generic), give mode a converter that raises ValueError with ErrorMessages.EMBEDDED_NULL_CHARACTER for a null after the str check, and switch dont_inherit to ClinicConversion.Boolean.

3. complex(real, imag) ignores __complex__ of an int subclass when imag is a complex
class Good(int):
    def __complex__(self):
        return 5 + 0j

class Bad(int):
    def __complex__(self):
        return frozenset()
Expression GraalPy CPython
complex(Good(1), 2j) (-1+0j) (3+0j)
complex(Bad(1), 2j) (-1+0j) TypeError: __complex__ returned non-complex (type frozenset)
complex(Good(1), 2 ** 70) (1+1.1805916207174113e+21j) (5+1.1805916207174113e+21j)

ComplexNewNode.complexFromPIntComplex (ComplexBuiltins.java#L509-L514) and the PInt overload of complexFromLongLong (#L334-L340) are fast paths for a PInt first argument with a complex or a large int second one. An instance of an int subclass is a PInt too, so it is converted by its integer value and its __complex__ is never called. CPython calls try_complex_special_method(r) for every first argument that is not an exact complex (complexobject.c#L936).

Fix suggestion

Guard complexFromPIntComplex and the PInt overload of complexFromLongLong on an exact int first argument, so a subclass instance falls through to the generic specializations, which call __complex__.

4. sum() rejects a str or bytes start before it gets the iterator
class RaisingIter:
    def __iter__(self):
        raise KeyError('iter')
Expression GraalPy CPython
sum(RaisingIter(), 'x') TypeError: sum() can't sum strings [use ''.join(seq) instead] KeyError: 'iter'
sum(RaisingIter(), b'x') TypeError: sum() can't sum bytes [use b''.join(seq) instead] KeyError: 'iter'
sum([], 'x') TypeError: sum() can't sum strings [use ''.join(seq) instead] TypeError: sum() can't sum strings [use ''.join(seq) instead]

SumFunctionNode.sum (BuiltinFunctions.java#L1877-L1886) checks the type of start and only then calls PyObjectGetIter. CPython's builtin_sum_impl gets the iterator first (bltinmodule.c#L2519-L2536).

Fix suggestion

Move the getIter.execute(...) call in SumFunctionNode.sum above the checks of start.

5. list() calls __len__ of an argument that is not iterable
class LenOnly:
    def __len__(self):
        raise KeyError('len')
Expression GraalPy CPython
list(LenOnly()) KeyError: 'len' TypeError: 'LenOnly' object is not iterable
set(LenOnly()) TypeError: 'LenOnly' object is not iterable TypeError: 'LenOnly' object is not iterable

ListInitNode.listIterable (ListBuiltins.java#L282-L283) asks the argument for its length before it calls PyObjectGetIter. CPython's list_extend gets the iterator first and the length hint second (listobject.c#L912-L918). list.extend(), list += x and tuple() ask for the length first in the same way.

Fix suggestion

Swap the two calls in listIterable, so getIter runs before lenNode.

6. super attribute lookup never hashes a str subclass name
class RaisingHash(str):
    def __hash__(self):
        raise KeyError('hash')

class StrHash(str):
    def __hash__(self):
        return 'x'
Expression GraalPy CPython
getattr(super(int, 1), RaisingHash('x'), None) None KeyError: 'hash'
hasattr(super(int, 1), RaisingHash('x')) False KeyError: 'hash'
getattr(super(int, 1), StrHash('x'), None) None TypeError: __hash__ method should return an integer

SuperBuiltins.GetAttributeNode.get converts the name to a TruffleString (SuperBuiltins.java#L516) and searches the MRO with it (#L528), so the __hash__ of a str subclass is never called. CPython's _super_lookup_descr uses the name object itself as the key in each MRO dict (typeobject.c#L10345), which hashes it.

Fix suggestion

In get, when the name is not an exact str, hash it with PyObjectHashNode once the MRO lookup has run, so an exception from __hash__ propagates.

7. csv.register_dialect() never hashes a str subclass name
import csv

class RaisingHash(str):
    def __hash__(self):
        raise KeyError('hash')

class StrHash(str):
    def __hash__(self):
        return 'x'
Expression GraalPy CPython
csv.register_dialect(RaisingHash('a')) None KeyError: 'hash'
csv.register_dialect(StrHash('b')) None TypeError: __hash__ method should return an integer

CSVRegisterDialectNode.register converts the name with CastToTruffleStringNode and stores the dialect under the converted string (CSVModuleBuiltins.java#L143-L155). CPython only checks PyUnicode_Check(name_obj) and inserts the object it was given (_csv.c#L1538-L1548), which hashes it. unregister_dialect and get_dialect already pass the name object to the dict; the lookup behind csv.reader(..., dialect=name) converts a str subclass name as well (CSVDialectBuiltins.java#L239-L241).

Fix suggestion

In register, check the name with PyUnicodeCheckNode and pass nameObj to PyDictSetItem, and pass the name object to getDialect in CSVDialectBuiltins so both sides use the same key.

8. type() accepts an mro() result without the new class
class Meta(type):
    def mro(cls):
        return type.mro(cls)[1:]
Expression GraalPy CPython
Meta('X', (), {}) <class '__main__.X'> TypeError: super(type, obj): obj must be an instance or subtype of type
Meta('X', (), {'f': lambda self: 1})().f() AttributeError: 'X' object has no attribute 'f' not reached

CreateTypeNode fills the super object used for __init_subclass__ directly with superObject.init(newType, newType, newType) (TypeNodes.java#L1968-L1971). CPython's type_new_init_subclass calls super(type, type) (typeobject.c#L10015-L10018), whose supercheck requires the class to be in its own MRO, so class creation fails. The message shown is 3.12's; 3.13 words it super(type, obj): obj (type X) is not an instance or subtype of type (X).

Fix suggestion

Before superObject.init, raise the TypeError of super() when newType is not in its own MRO.

9. A custom mro() without object changes the solid base of a class
class OnlySelf(type):
    def mro(cls):
        return (cls,)

class AppendB(type):
    def mro(cls):
        return (cls, B)

B = OnlySelf('B', (), {})
Expression GraalPy CPython
type('C', (B, int), {}) TypeError: multiple bases have instance lay-out conflict <class '__main__.C'>
AppendB('A', (), {}).__mro__ TypeError: mro() returned base with unsuitable layout ('OnlySelf') (<class '__main__.A'>, <class '__main__.B'>)

GetSolidBaseNode.shapeDiffers compares the __new__ found along the MRO of the class and of its base (TypeNodes.java#L1315-L1317). The MRO of B has no object, so no __new__ is found and B counts as its own solid base. CPython's shape_differs compares only tp_basicsize and tp_itemsize (typeobject.c#L2820-L2826), which a custom mro() cannot change, so the solid base of B is object.

Fix suggestion

In shapeDiffers, look __new__ up along the __base__ chain of each class instead of its MRO.

10. __build_class__ does not check the __class__ cell
import types
from typing import NamedTuple

def define():
    class X(NamedTuple):
        a: int
        def foo(self):
            return super()
    return X
Expression GraalPy CPython
define() <class '__main__.define.<locals>.X'> RuntimeError: __class__ not set defining 'X' as <class '__main__.define.<locals>.X'>. Was __classcell__ propagated to type.__new__?
define()(1).foo() RuntimeError: super(): empty __class__ cell not reached
__build_class__(lambda: types.CellType(), 'X') <class '__main__.X'> RuntimeError: __class__ not set defining 'X' as <class '__main__.X'>. Was __classcell__ propagated to type.__new__?

BuildClassNode drops the value the class body returns (BuiltinFunctions.java#L2355), which is the __class__ cell, and returns the result of the metaclass call unchecked; a comment marks the spot (#L2369-L2375). CPython's builtin___build_class__ compares the cell with the new class (bltinmodule.c#L210-L226) and raises RuntimeError when the cell is still empty, as it is after typing.NamedTupleMeta builds the class without __classcell__, and TypeError when it holds another class.

Fix suggestion

Keep the result of invokeBody.execute. After the metaclass call, when it is a cell, the result is a type and the cell does not hold that type, raise RuntimeError for an empty cell and TypeError otherwise.

11. UnicodeDecodeError accepts a str object
Expression GraalPy CPython
UnicodeDecodeError('ascii', 'bytes', 0, 1, 'ouch') UnicodeDecodeError('ascii', 'bytes', 0, 1, 'ouch') TypeError: a bytes-like object is required, not 'str'
UnicodeDecodeError('ascii', 'bytes', 0, 1, 'ouch').object b'bytes' not reached

UnicodeDecodeErrorInitNode converts the second argument with GetArgAsBytesNode (UnicodeDecodeErrorBuiltins.java#L124), whose doString specialization encodes a str to bytes (UnicodeErrorBuiltins.java#L126-L134). CPython's UnicodeDecodeError_init takes the object through the buffer protocol only (exceptions.c#L3065-L3068).

Fix suggestion

Remove doString and let a str reach doOther, where PyObjectGetBuffer raises the TypeError. UnicodeDecodeError is the only user of the node; the one internal caller that still passes a string, PyUnicode_FromStringAndSize in PythonCextUnicodeBuiltins, has to pass the bytes instead.

12. str() of a bytes subclass calls the subclass __repr__
class B(bytes):
    def __repr__(self):
        return 'repr'

class BA(bytearray):
    def __repr__(self):
        return 'repr'
Expression GraalPy CPython
str(B(b'x')) 'repr' "b'x'"
format(B(b'x')) 'repr' "b'x'"
str(BA(b'x')) 'repr' "BA(b'x')"
'__str__' in vars(bytes) False True

bytes and bytearray define only tp_repr (BytesBuiltins.java#L289-L298, ByteArrayBuiltins.java#L389-L411) and inherit the tp_str of object, which calls the tp_repr slot of the instance's type (ObjectBuiltins.java#L482-L497). CPython gives both their own tp_str, bytes_str (bytesobject.c#L1406-L1416) and bytearray_str (bytearrayobject.c#L1015-L1025), which format with the C repr function directly.

Fix suggestion

Add a tp_str slot to BytesBuiltins and ByteArrayBuiltins that reuses the ReprNode of the type.

13. weakref.proxy() never returns a CallableProxyType
import weakref

class C:
    pass

c = C()
Expression GraalPy CPython
type(weakref.proxy(C)) <class 'weakref.ProxyType'> <class 'weakref.CallableProxyType'>
callable(weakref.proxy(c)) True False
weakref.proxy(c)() TypeError: 'C' object is not callable TypeError: 'weakref.ProxyType' object is not callable

NewProxyTypeNode always instantiates PProxyType (ProxyTypeBuiltins.java#L189), and tp_call sits on that type (#L331-L343); PCallableProxyType is declared without slots and never used (PythonBuiltinClassType.java#L586-L587). CPython's PyWeakref_NewProxy switches to _PyWeakref_CallableProxyType for a callable referent (weakrefobject.c#L874-L876), and only that type has tp_call.

Fix suggestion

In NewProxyTypeNode, pick PCallableProxyType when PyCallableCheckNode accepts the referent. Give PCallableProxyType the slots of ProxyTypeBuiltins plus tp_call, and move tp_call off PProxyType.

14. Coroutine and async generator objects have no __name__ / __qualname__
import asyncio

async def coro():
    pass

async def agen():
    yield 1

c, g = coro(), agen()
Expression GraalPy CPython
c.__name__ AttributeError: 'coroutine' object has no attribute '__name__' 'coro'
g.__qualname__ AttributeError: 'async_generator' object has no attribute '__qualname__' 'agen'
repr(g) <async_generator object at 0x...> <async_generator object agen at 0x...>
asyncio.coroutines._format_coroutine(c) <coroutine without __name__>() running at ... coro() running at ...

The __name__ and __qualname__ getters and setters live in GeneratorBuiltins, which extends generator only. CoroutineBuiltins and AsyncGeneratorBuiltins define neither, and async_generator has no tp_repr. CPython gives all three types the same getters (coro_getsetlist, async_gen_getsetlist).

Fix suggestion

Move NameNode and QualnameNode into a builtins class registered on PGenerator, PCoroutine and PAsyncGenerator (the Java objects are all PGenerator), and add a tp_repr to AsyncGeneratorBuiltins that prints the qualified name like the coroutine one.

15. types.FunctionType(code, globals) ignores the code object's names
import types

def func():
    pass

class K:
    def meth(self):
        pass
Expression GraalPy CPython
types.FunctionType(func.__code__, {}).__name__ '<lambda>' 'func'
types.FunctionType(func.__code__, {}) <function <lambda> at 0x...> <function func at 0x...>
types.FunctionType(K.meth.__code__, {}, 'nm').__qualname__ 'nm' 'K.meth'
types.FunctionType(K.meth.__code__, {}, None, (1,)).__qualname__ 'meth' 'K.meth'

FunctionBuiltins.FunctionNode passes the constant T_LAMBDA_NAME when name is omitted and argdefs is not given, and every specialization goes through a PFactory.createFunction overload that uses the name as the qualified name. CPython's func_new_impl builds the function with PyFunction_New, which takes co_name and co_qualname from the code object (funcobject.c#L151-L156), and replaces only __name__ when name is given.

Fix suggestion

In every FunctionNode specialization, pass code.getName() when name is None and code.getQualName() as the qualified name.

16. object.__reduce_ex__ finds __getnewargs_ex__ / __getnewargs__ through __getattr__
import copy

class Spam(dict):
    def __getattr__(self, name):
        return self.get(name)

class G:
    def __getnewargs__(self):
        return (1,)

g = G()
g.__getnewargs_ex__ = lambda: ((9,), {})
Expression GraalPy CPython
copy.deepcopy(Spam(ham=5)) TypeError: 'NoneType' object is not callable {'ham': 5}
Spam(ham=5).__reduce_ex__(4) TypeError: 'NoneType' object is not callable (<function __newobj__ at 0x...>, (<class '__main__.Spam'>,), None, None, <dict_itemiterator object at 0x...>)
g.__reduce_ex__(4)[1] (<class '__main__.G'>, 9) (<class '__main__.G'>, 1)

ObjectNodes.GetNewArgsNode fetches both names with PyObjectLookupAttr, a full attribute lookup that sees instance attributes and falls back to __getattr__. CPython's _PyObject_GetNewArguments uses _PyObject_LookupSpecial, which looks only on the type (typeobject.c#L6083, #L6134).

Fix suggestion

In GetNewArgsNode, look both names up with LookupSpecialMethodNode on the object's class and call the result with the object as receiver.

17. ast.iter_fields() accepts an object without _fields
import ast
Expression GraalPy CPython
ast.unparse(list) '' AttributeError: type object 'list' has no attribute '_fields'
list(ast.iter_fields(list)) [] AttributeError: type object 'list' has no attribute '_fields'
list(ast.walk(list)) [<class 'list'>] AttributeError: type object 'list' has no attribute '_fields'

The bundled ast.py wraps the loop of iter_fields in a second try/except AttributeError marked GraalPy: ignore missing _fields (ast.py#L272-L285), so a missing _fields yields nothing. CPython's iter_fields (ast.py#L257-L266) reads node._fields unguarded. iter_child_nodes, walk, NodeVisitor.generic_visit and unparse all go through it.

Fix suggestion

Drop the outer try/except AttributeError from iter_fields, which restores the CPython body. The bundled test_ast and test_unparse pass without it.

18. heapq functions accept a heap that is not a list
import heapq, collections
Expression GraalPy CPython
heapq.heappushpop(None, 1) 1 TypeError: heappushpop() argument 1 must be list, not None
heapq.heapify(()) None TypeError: heapify() argument must be list, not tuple
heapq.heappush(None, 1) AttributeError: 'NoneType' object has no attribute 'append' TypeError: heappush() argument 1 must be list, not None
heapq.heappop(None) AttributeError: 'NoneType' object has no attribute 'pop' TypeError: heappop() argument must be list, not None
heapq.heapreplace((), 1) IndexError: tuple index out of range TypeError: heapreplace() argument 1 must be list, not tuple
heapq.heappush(collections.deque([2]), 1) None, the deque becomes deque([2, 1]) TypeError: heappush() argument 1 must be list, not collections.deque

GraalPy has no _heapq module, so the from _heapq import * at the end of heapq.py fails and the five functions and their private max-heap variants stay the pure-Python versions, which use any object they are given. CPython runs the C versions, which declare the heap as object(subclass_of='&PyList_Type'), so the generated parser raises TypeError for anything else (_heapqmodule.c.h#L33-L36).

Fix suggestion

Check issubclass(type(heap), list) at the top of heappush, heappop, heapreplace, heappushpop, heapify and the three _max variants in lib-python/3/heapq.py and raise TypeError otherwise, or add a Java _heapq module whose functions take only a list.

19. itertools.combinations, combinations_with_replacement, permutations and product do not check the length hint of their iterable
import itertools

class Endless:
    def __getitem__(self, i):
        return i

    def __length_hint__(self):
        return -1

class Failing:
    def __getitem__(self, i):
        raise KeyError(i)

    def __length_hint__(self):
        return b';'
Expression GraalPy CPython
itertools.combinations(Endless(), 1) never returns ValueError: __length_hint__() should return >= 0
itertools.combinations_with_replacement(Endless(), 1) never returns ValueError: __length_hint__() should return >= 0
itertools.permutations(Endless()) never returns ValueError: __length_hint__() should return >= 0
itertools.product(Endless()) never returns ValueError: __length_hint__() should return >= 0
itertools.permutations(Failing()) KeyError: 0 TypeError: __length_hint__ must be an integer, not bytes

The four constructors collect their argument with IteratorNodes.ToArrayNode, whose generic case only iterates. CPython collects it with PySequence_Tuple, which calls PyObject_LengthHint before requesting the first item, so an invalid __len__ or __length_hint__ is reported first. tuple() already does this in ConstructTupleNode.

Fix suggestion

In the generic case of ToArrayNode, call IteratorNodes.GetLength on the iterable after PyObjectGetIter and before the loop. The only other caller passes a list, which never reaches that case. A list, tuple or str subclass still takes the storage fast path, which calls neither its __len__ nor its __iter__; that is a separate, existing difference.

                         @Cached PyObjectGetIter getIter,
+                        @Cached GetLength lenNode,
                         @Cached PyIterNextNode nextNode) {
             Object it = getIter.execute(frame, inliningTarget, iterable);
+            lenNode.execute(frame, inliningTarget, iterable);
             ArrayList<Object> result = new ArrayList<>();
20. itertools.tee and batched reject an n outside the 32-bit range before checking its sign
import itertools
Expression GraalPy CPython
itertools.tee([], -2**32 - 1) OverflowError: Python int too large to convert to Java int ValueError: n must be >= 0
itertools.batched([], -2**32 - 1) OverflowError: Python int too large to convert to Java int ValueError: n must be at least one
itertools.batched([], 2**32 + 1) OverflowError: Python int too large to convert to Java int <itertools.batched object at 0x...>

TeeNode and BatchedNode convert n with ClinicConversion.Int, so a value outside the Java int range fails in the converter before the range check runs. CPython converts n to Py_ssize_t and then rejects n < 0 in tee and n < 1 in batched.

Fix suggestion

Convert n with ClinicConversion.LongIndex in both builtins and run the range checks on the long. batched can cap the stored batch size at Integer.MAX_VALUE, and tee can narrow a positive n with PInt.long2int.

21. __main__.__loader__ is None for a script run from a file
# script.py, run as `graalpy script.py`
print(type(eval('__loader__')))
print(__loader__.get_source('__main__'))
Expression GraalPy CPython
type(eval('__loader__')) <class 'NoneType'> <class '_frozen_importlib_external.SourceFileLoader'>
__loader__.get_source('__main__') AttributeError: 'NoneType' object has no attribute 'get_source' the script's source

__main__ is created with __loader__ = None (PythonModule.java#L80), and RunPathNode.runFile sets only __file__ before it runs the script. CPython's _PyRun_SimpleFileObject installs a SourceFileLoader for every file that is not stdin (pythonrun.c#L452-L457).

Fix suggestion

In runFile, when the input path is not empty, set __main__.__loader__ to _frozen_importlib._bootstrap_external.SourceFileLoader('__main__', path). CPython makes __file__ absolute first; GraalPy keeps a relative script path, so the loader path stays relative with it unless __file__ is made absolute as well.

Expected behavior

The CPython column of each item.

Stack trace

Additional context

No response

主要语言
Python
星标
1.7k
派生
167
平均合并
3 天 11 小时
30 天内合并 PR
68

环境准备

在 Codespaces 中打开

在浏览器里用你自己的 GitHub 账号启动这个项目的开发容器。

  • 没有 Dockerfile 或 Docker Compose 文件
  • 没有 Pull Request 模板
  • 阅读贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

oracle/graalpython 的其他 Issue

查看 oracle/graalpython 的全部 Issue

相似的 Issue

更多 Python Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。