X Tutup
Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion Lib/test/test_str.py
Original file line number Diff line number Diff line change
Expand Up @@ -2414,7 +2414,6 @@ def test_ucs4(self):
else:
self.fail("Should have raised UnicodeDecodeError")

@unittest.expectedFailure # TODO: RUSTPYTHON; AssertionError: <class 'str'> is not <class 'test.test_str.StrSubclass'>
def test_conversion(self):
# Make sure __str__() works properly
class StrWithStr(str):
Expand Down
9 changes: 3 additions & 6 deletions crates/vm/src/builtins/str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -394,13 +394,10 @@ impl Constructor for PyStr {
type Args = StrArgs;

fn slot_new(cls: PyTypeRef, func_args: FuncArgs, vm: &VirtualMachine) -> PyResult {
// Optimization: return exact str as-is (only when no encoding/errors provided)
if cls.is(vm.ctx.types.str_type)
&& func_args.args.len() == 1
&& func_args.kwargs.is_empty()
&& func_args.args[0].class().is(vm.ctx.types.str_type)
// Optimization: for exact str, return PyObject_Str result as-is
if cls.is(vm.ctx.types.str_type) && func_args.args.len() == 1 && func_args.kwargs.is_empty()
{
return Ok(func_args.args[0].clone());
return func_args.args[0].str(vm).map(Into::into);
}

let args: Self::Args = func_args.bind(vm)?;
Expand Down
27 changes: 27 additions & 0 deletions extra_tests/snippets/builtin_str_subclass.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,33 @@ def __init__(self, value):
assert y + " other" == "1 other"
assert y.x == "substr"


class ReprStrSubclass(str):
pass


class WithStr:
def __init__(self, value):
self.value = value

def __str__(self):
return self.value


class WithRepr:
def __init__(self, value):
self.value = value

def __repr__(self):
return self.value


str_value = ReprStrSubclass("abc")
assert str(WithStr(str_value)) is str_value

repr_value = ReprStrSubclass("<abc>")
assert str(WithRepr(repr_value)) is repr_value

## Base strings currently get an attribute dict, but shouldn't.
# with assert_raises(AttributeError):
# "hello".x = 5
Loading
X Tutup