Fix sys.getsizeof (#4604)

This commit is contained in:
Steve Shi
2023-03-01 22:56:34 +02:00
committed by GitHub
parent e731e658ba
commit 166959db41
4 changed files with 19 additions and 9 deletions

View File

@@ -66,8 +66,6 @@ class IoctlTests(unittest.TestCase):
# Test with a larger buffer, just for the record.
self._check_ioctl_mutate_len(2048)
# TODO: RUSTPYTHON
@unittest.expectedFailure
def test_ioctl_signed_unsigned_code_param(self):
if not pty:
raise unittest.SkipTest('pty module required')

View File

@@ -437,8 +437,6 @@ class OrderedDictTests:
od.move_to_end('c')
self.assertEqual(list(od), list('bac'))
# TODO: RUSTPYTHON
@unittest.expectedFailure
def test_sizeof(self):
OrderedDict = self.OrderedDict
# Wimpy test: Just verify the reported size is larger than a regular dict

View File

@@ -17,12 +17,12 @@ mod sys {
types::PyStructSequence,
version,
vm::{Settings, VirtualMachine},
AsObject, PyObjectRef, PyRef, PyRefExact, PyResult,
AsObject, PyObject, PyObjectRef, PyRef, PyRefExact, PyResult,
};
use num_traits::ToPrimitive;
use std::{
env::{self, VarError},
mem, path,
path,
sync::atomic::Ordering,
};
@@ -419,10 +419,23 @@ mod sys {
vm.recursion_limit.get()
}
#[derive(FromArgs)]
struct GetsizeofArgs {
obj: PyObjectRef,
#[pyarg(any, optional)]
default: Option<PyObjectRef>,
}
#[pyfunction]
fn getsizeof(obj: PyObjectRef) -> usize {
// TODO: implement default optional argument.
mem::size_of_val(&obj)
fn getsizeof(args: GetsizeofArgs, vm: &VirtualMachine) -> PyResult {
let sizeof = || -> PyResult<usize> {
let res = vm.call_special_method(args.obj, identifier!(vm, __sizeof__), ())?;
let res = res.try_index(vm)?.try_to_primitive::<usize>(vm)?;
Ok(res + std::mem::size_of::<PyObject>())
};
sizeof()
.map(|x| vm.ctx.new_int(x).into())
.or_else(|err| args.default.ok_or(err))
}
#[pyfunction]

View File

@@ -202,6 +202,7 @@ declare_const_name! {
__str__,
__sub__,
__subclasscheck__,
__sizeof__,
__truediv__,
__trunc__,
__xor__,