From cb4df01aca30e0bbda828a2f98fb409c0c651a83 Mon Sep 17 00:00:00 2001 From: snowapril Date: Sat, 28 Aug 2021 17:54:50 +0900 Subject: [PATCH] Implement bytes.__bytes__ This commit implement `bytes.__bytes__` in cpython 3.11 for typing module. * https://docs.python.org/3.11/whatsnew/3.11.html#other-cpython-implementation-changes * https://bugs.python.org/issue24234 Signed-off-by: snowapril --- extra_tests/snippets/bytes.py | 10 ++++++++++ vm/src/builtins/bytes.rs | 9 +++++++++ 2 files changed, 19 insertions(+) diff --git a/extra_tests/snippets/bytes.py b/extra_tests/snippets/bytes.py index d9489a613..7cbd38010 100644 --- a/extra_tests/snippets/bytes.py +++ b/extra_tests/snippets/bytes.py @@ -615,6 +615,16 @@ assert b'\xe4\xb8\xad\xe6\x96\x87\xe5\xad\x97'.decode('utf-8') == '中文字' assert b'rust%bpython%b' % (b' ', b'!') == b'rust python!' assert b'x=%i y=%f' % (1, 2.5) == b'x=1 y=2.500000' +# __bytes__ +foo = b'foo\x00bar' +assert foo.__bytes__() == foo +assert type(foo.__bytes__()) == bytes +class bytes_subclass(bytes): + pass +bar = bytes_subclass(b'bar\x00foo') +assert bar.__bytes__() == bar +assert type(bar.__bytes__()) == bytes + class A: def __bytes__(self): return b"bytess" diff --git a/vm/src/builtins/bytes.rs b/vm/src/builtins/bytes.rs index f8d35eb0d..7e91719fd 100644 --- a/vm/src/builtins/bytes.rs +++ b/vm/src/builtins/bytes.rs @@ -128,6 +128,15 @@ impl PyBytes { &self.inner.elements } + #[pymethod(magic)] + fn bytes(zelf: PyRef, vm: &VirtualMachine) -> PyRef { + if zelf.is(&vm.ctx.types.bytes_type) { + zelf + } else { + PyBytes::from(zelf.inner.clone()).into_ref(vm) + } + } + #[pymethod(magic)] fn sizeof(&self) -> usize { size_of::() + self.inner.elements.len() * size_of::()