Add support for __bytes__ method

This commit is contained in:
coolreader18
2019-12-02 17:58:43 -06:00
parent 42b5fbc52d
commit d4a1021473
2 changed files with 13 additions and 2 deletions

View File

@@ -614,3 +614,9 @@ assert b'\xe4\xb8\xad\xe6\x96\x87\xe5\xad\x97'.decode('utf-8') == '中文字'
# mod
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'
class A:
def __bytes__(self):
return b"bytess"
assert bytes(A()) == b"bytess"

View File

@@ -86,15 +86,20 @@ impl ByteInnerNewOptions {
);
}
obj => {
// TODO: only support this method in the bytes() constructor
if let Some(bytes_method) = vm.get_method(obj.clone(), "__bytes__") {
let bytes = vm.invoke(&bytes_method?, vec![])?;
return PyByteInner::try_from_object(vm, bytes);
}
let elements = vm.extract_elements(&obj).or_else(|_| {
Err(vm.new_type_error(format!(
"cannot convert '{}' object to bytes",
obj.class().name
)))
});
})?;
let mut data_bytes = vec![];
for elem in elements? {
for elem in elements {
let v = objint::to_int(vm, &elem, &BigInt::from(10))?;
if let Some(i) = v.to_u8() {
data_bytes.push(i);