Skip to content

Commit 9435e01

Browse files
committed
Support __bytes
Fixes #1763
1 parent 5971794 commit 9435e01

File tree

2 files changed

+21
-4
lines changed

2 files changed

+21
-4
lines changed

py/objstr.c

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
#include "py/unicode.h"
3232
#include "py/objstr.h"
3333
#include "py/objlist.h"
34+
#include "py/objtype.h"
3435
#include "py/runtime.h"
3536
#include "py/stackctrl.h"
3637

@@ -211,6 +212,10 @@ STATIC mp_obj_t bytes_make_new(const mp_obj_type_t *type_in, size_t n_args, cons
211212
return mp_const_empty_bytes;
212213
}
213214

215+
if (n_args > 1) {
216+
goto wrong_args;
217+
}
218+
214219
if (MP_OBJ_IS_STR(args[0])) {
215220
if (n_args < 2 || n_args > 3) {
216221
goto wrong_args;
@@ -226,10 +231,6 @@ STATIC mp_obj_t bytes_make_new(const mp_obj_type_t *type_in, size_t n_args, cons
226231
return MP_OBJ_FROM_PTR(o);
227232
}
228233

229-
if (n_args > 1) {
230-
goto wrong_args;
231-
}
232-
233234
if (MP_OBJ_IS_SMALL_INT(args[0])) {
234235
mp_int_t len = MP_OBJ_SMALL_INT_VALUE(args[0]);
235236
if (len < 0) {
@@ -241,6 +242,13 @@ STATIC mp_obj_t bytes_make_new(const mp_obj_type_t *type_in, size_t n_args, cons
241242
return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
242243
}
243244

245+
// check if __bytes__ exists, and if so delegate to it
246+
mp_obj_t dest[2];
247+
mp_load_method_maybe(args[0], MP_QSTR___bytes__, dest);
248+
if (dest[0] != MP_OBJ_NULL) {
249+
return mp_call_method_n_kw(0, 0, dest);
250+
}
251+
244252
// check if argument has the buffer protocol
245253
mp_buffer_info_t bufinfo;
246254
if (mp_get_buffer(args[0], &bufinfo, MP_BUFFER_READ)) {

tests/basics/class_bytes.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
class C1:
2+
def __init__(self, value):
3+
self.value = value
4+
5+
def __bytes__(self):
6+
return self.value
7+
8+
c1 = C1(b"class 1")
9+
print(bytes(c1))

0 commit comments

Comments
 (0)