From 2ab819a724389b0bdb3213b2513502fc9e76b29b Mon Sep 17 00:00:00 2001 From: Anurag Bhat <90216905+faze-geek@users.noreply.github.com> Date: Tue, 12 Mar 2024 22:25:54 +0530 Subject: [PATCH] Modify string constructor to allow no arguments (#226) * Modify String Constructor * Add check to restrict arguments --- src/pocketpy.cpp | 6 +++++- tests/04_str.py | 1 + 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/src/pocketpy.cpp b/src/pocketpy.cpp index 790189a1..ce4df652 100644 --- a/src/pocketpy.cpp +++ b/src/pocketpy.cpp @@ -496,7 +496,11 @@ void init_builtins(VM* _vm) { }); // tp_str - _vm->bind_constructor<2>(_vm->_t(VM::tp_str), PK_LAMBDA(vm->py_str(args[1]))); + _vm->bind_constructor<-1>(_vm->_t(VM::tp_str), [](VM* vm, ArgsView args) { + if(args.size() == 1) return VAR(Str()); + if(args.size() > 2) vm->TypeError("str() takes at most 1 argument"); + return vm->py_str(args[1]); + }); _vm->bind__hash__(VM::tp_str, [](VM* vm, PyObject* _0) { return (i64)_CAST(Str&, _0).hash(); diff --git a/tests/04_str.py b/tests/04_str.py index fe950742..4c3d5ef8 100644 --- a/tests/04_str.py +++ b/tests/04_str.py @@ -14,6 +14,7 @@ assert repr('\\\n\t\'\r\b\x48') == r"'\\\n\t\'\r\bH'" a = '' b = 'test' c ='test' +assert a == str() assert len(a) == 0 assert len(b) == 4 assert b == c