graalpython icon indicating copy to clipboard operation
graalpython copied to clipboard

[Bug]: ascii() does not preserve str subclass type for all-ASCII repr

Open jseop-lim opened this issue 8 months ago • 2 comments

Describe the bug

ascii() returns a plain str instead of preserving the str subclass type when __repr__ returns an all-ASCII str subclass instance. This is a CPython compatibility issue.

Operating system

Linux

CPU architecture

ARM64

GraalPy version

25.0.2

JDK version

No response

Context configuration

No response

Steps to reproduce

class MyStr(str):
    pass

class Foo:
    def __repr__(self):
        return MyStr('hello')

result = ascii(Foo())
print(result)
print(type(result))

GraalPy (Actual):

hello
<class 'str'>

CPython (Expected):

hello
<class '__main__.MyStr'>

Additional context

Root Cause

PyObjectAsciiNode.java#L77-L87 uses PyObjectReprAsTruffleStringNode, which converts the repr result to a raw TruffleString via CastToTruffleStringNode, discarding the PString subclass wrapper. When the repr is all-ASCII, the node returns that bare TruffleString — a plain str — instead of the original object.

CPython reference: Objects/object.c#L514-L523 — PyObject_ASCII does if (PyUnicode_IS_ASCII(repr)) return repr, preserving the str subclass type.

Fix Suggestion

Use PyObjectReprAsObjectNode instead of PyObjectReprAsTruffleStringNode and return the original repr object on the all-ASCII fast path to preserve the str subclass type.

jseop-lim avatar Mar 16 '26 10:03 jseop-lim

Hey! I may be able to help with this bug.

I build custom fixes for Python projects and automation systems.

If you'd like help resolving this issue quickly feel free to reach out.

Happy to take a look 👍

FocusMode-coder avatar Mar 16 '26 11:03 FocusMode-coder

@msimacek Thanks for fixing this!

jseop-lim avatar Mar 17 '26 11:03 jseop-lim