Skip to content

Commit 9de155a

Browse files
authored
Merge pull request #2220 from tannewt/support_dunder_bytes
Support __bytes__
2 parents 756e4a4 + 1610d06 commit 9de155a

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

@@ -226,10 +227,6 @@ STATIC mp_obj_t bytes_make_new(const mp_obj_type_t *type_in, size_t n_args, cons
226227
return MP_OBJ_FROM_PTR(o);
227228
}
228229

229-
if (n_args > 1) {
230-
goto wrong_args;
231-
}
232-
233230
if (MP_OBJ_IS_SMALL_INT(args[0])) {
234231
mp_int_t len = MP_OBJ_SMALL_INT_VALUE(args[0]);
235232
if (len < 0) {
@@ -241,6 +238,17 @@ STATIC mp_obj_t bytes_make_new(const mp_obj_type_t *type_in, size_t n_args, cons
241238
return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
242239
}
243240

241+
if (n_args > 1) {
242+
goto wrong_args;
243+
}
244+
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)