From c8d581cfe783d7328cc5645a294709fff202f881 Mon Sep 17 00:00:00 2001 From: BLUELOVETH Date: Wed, 20 Sep 2023 10:33:22 +0800 Subject: [PATCH] move `__repr__` of list and tuple into cpp --- python/builtins.py | 10 -------- src/pocketpy.cpp | 57 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+), 10 deletions(-) diff --git a/python/builtins.py b/python/builtins.py index 9558a164..4abb8187 100644 --- a/python/builtins.py +++ b/python/builtins.py @@ -157,16 +157,6 @@ def __f(self, width: int, fillchar=' '): str.ljust = __f ##### list ##### -list.__repr__ = lambda self: '[' + ', '.join([repr(i) for i in self]) + ']' -list.__json__ = lambda self: '[' + ', '.join([i.__json__() for i in self]) + ']' -tuple.__json__ = lambda self: '[' + ', '.join([i.__json__() for i in self]) + ']' - -def __f(self): - if len(self) == 1: - return '(' + repr(self[0]) + ',)' - return '(' + ', '.join([repr(i) for i in self]) + ')' -tuple.__repr__ = __f - def __qsort(a: list, L: int, R: int, key): if L >= R: return; mid = a[(R+L)//2]; diff --git a/src/pocketpy.cpp b/src/pocketpy.cpp index 22855fdf..55c8af2a 100644 --- a/src/pocketpy.cpp +++ b/src/pocketpy.cpp @@ -667,6 +667,63 @@ void init_builtins(VM* _vm) { }); /************ list ************/ + // list.__repr__ = lambda self: '[' + ', '.join([repr(i) for i in self]) + ']' + // list.__json__ = lambda self: '[' + ', '.join([i.__json__() for i in self]) + ']' + // tuple.__json__ = lambda self: '[' + ', '.join([i.__json__() for i in self]) + ']' + + // def __f(self): + // if len(self) == 1: + // return '(' + repr(self[0]) + ',)' + // return '(' + ', '.join([repr(i) for i in self]) + ')' + // tuple.__repr__ = __f + + _vm->bind__repr__(_vm->tp_list, [](VM* vm, PyObject* _0){ + List& iterable = _CAST(List&, _0); + std::stringstream ss; + ss << '['; + for(int i=0; ipy_repr(iterable[i]); + if(i != iterable.size()) ss << ','; + } + ss << ']'; + return VAR(ss.str()); + }); + + _vm->bind__json__(_vm->tp_list, [](VM* vm, PyObject* _0){ + List& iterable = _CAST(List&, _0); + std::stringstream ss; + ss << '['; + for(int i=0; ipy_json(iterable[i]); + if(i != iterable.size()) ss << ','; + } + ss << ']'; + return VAR(ss.str()); + }); + + _vm->bind__repr__(_vm->tp_tuple, [](VM* vm, PyObject* _0){ + Tuple& iterable = _CAST(Tuple&, _0); + std::stringstream ss; + ss << '('; + for(int i=0; ipy_repr(iterable[i]); + } + ss << ')'; + return VAR(ss.str()); + }); + + _vm->bind__json__(_vm->tp_tuple, [](VM* vm, PyObject* _0){ + Tuple& iterable = _CAST(Tuple&, _0); + std::stringstream ss; + ss << '['; + for(int i=0; ipy_json(iterable[i]); + if(i != iterable.size()) ss << ','; + } + ss << ']'; + return VAR(ss.str()); + }); + _vm->bind_constructor<-1>("list", [](VM* vm, ArgsView args) { if(args.size() == 1+0) return VAR(List()); if(args.size() == 1+1){