diff --git a/src/collections.cpp b/src/collections.cpp index 9c85ff7f..65a17f1a 100644 --- a/src/collections.cpp +++ b/src/collections.cpp @@ -258,17 +258,11 @@ namespace pkpy // Return the position of x in the deque (at or after index start and before index stop). Returns the first match or raises ValueError if not found. PyDeque &self = _CAST(PyDeque &, args[0]); PyObject *obj = args[1]; - int start = 0, stop = self.dequeItems.size(); // default values - if (!vm->py_eq(args[2], vm->None)) - start = CAST(int, args[2]); - if (!vm->py_eq(args[3], vm->None)) - stop = CAST(int, args[3]); + int start = CAST_DEFAULT(int, args[2], 0); + int stop = CAST_DEFAULT(int, args[3], self.dequeItems.size()); int index = self.findIndex(vm, obj, start, stop); - if (index != -1) - return VAR(index); - else - vm->ValueError(_CAST(Str &, vm->py_repr(obj)) + " is not in deque"); - return vm->None; + if (index < 0) vm->ValueError(_CAST(Str &, vm->py_repr(obj)) + " is not in deque"); + return VAR(index); }); // NEW: returns the index of the given object in the deque vm->bind(type, "__contains__(self, obj) -> bool", diff --git a/src/pocketpy.cpp b/src/pocketpy.cpp index 68c861b6..fb3eac6a 100644 --- a/src/pocketpy.cpp +++ b/src/pocketpy.cpp @@ -803,10 +803,11 @@ void init_builtins(VM* _vm) { return vm->True; }); - _vm->bind_method<1>(VM::tp_list, "index", [](VM* vm, ArgsView args) { + _vm->bind(_vm->_t(VM::tp_list), "index(self, value, __start=0)", [](VM* vm, ArgsView args) { List& self = _CAST(List&, args[0]); PyObject* obj = args[1]; - for(int i=0; ipy_eq(self[i], obj)) return VAR(i); } vm->ValueError(_CAST(Str&, vm->py_repr(obj)) + " is not in list"); diff --git a/tests/05_list.py b/tests/05_list.py index 52227ee0..c9bdb7ee 100644 --- a/tests/05_list.py +++ b/tests/05_list.py @@ -116,3 +116,16 @@ assert A()[::, :2] == (slice(None, None, None), slice(None, 2, None)) assert A()['b':'c':1, :] == (slice('b', 'c', 1), slice(None, None, None)) assert A()[1:2, :A()[3:4, ::-1]] == (slice(1, 2, None), slice(None, (slice(3, 4, None), slice(None, None, -1)), None)) +a = [1, 2, 3] +assert a.index(2) == 1 +assert a.index(1) == 0 +assert a.index(3) == 2 + +assert a.index(2, 1) == 1 +assert a.index(1, 0) == 0 + +try: + a.index(1, 1) + exit(1) +except ValueError: + pass