Skip to content

Support __bytes__ #2220

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Oct 15, 2019
Merged
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
16 changes: 12 additions & 4 deletions py/objstr.c
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
#include "py/unicode.h"
#include "py/objstr.h"
#include "py/objlist.h"
#include "py/objtype.h"
#include "py/runtime.h"
#include "py/stackctrl.h"

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

if (n_args > 1) {
goto wrong_args;
}

if (MP_OBJ_IS_SMALL_INT(args[0])) {
mp_int_t len = MP_OBJ_SMALL_INT_VALUE(args[0]);
if (len < 0) {
Expand All @@ -241,6 +238,17 @@ STATIC mp_obj_t bytes_make_new(const mp_obj_type_t *type_in, size_t n_args, cons
return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
}

if (n_args > 1) {
goto wrong_args;
}

// check if __bytes__ exists, and if so delegate to it
mp_obj_t dest[2];
mp_load_method_maybe(args[0], MP_QSTR___bytes__, dest);
if (dest[0] != MP_OBJ_NULL) {
return mp_call_method_n_kw(0, 0, dest);
}

// check if argument has the buffer protocol
mp_buffer_info_t bufinfo;
if (mp_get_buffer(args[0], &bufinfo, MP_BUFFER_READ)) {
Expand Down
9 changes: 9 additions & 0 deletions tests/basics/class_bytes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
class C1:
def __init__(self, value):
self.value = value

def __bytes__(self):
return self.value

c1 = C1(b"class 1")
print(bytes(c1))