ソースを参照

`isinstance` support tuple

BLUELOVETH 2 年 前
コミット
393302ae85
2 ファイル変更26 行追加0 行削除
  1. 8 0
      src/pocketpy.cpp
  2. 18 0
      tests/40_class.py

+ 8 - 0
src/pocketpy.cpp

@@ -121,6 +121,14 @@ void init_builtins(VM* _vm) {
     });
 
     _vm->bind_builtin_func<2>("isinstance", [](VM* vm, ArgsView args) {
+        if(is_non_tagged_type(args[1], vm->tp_tuple)){
+            Tuple& types = _CAST(Tuple&, args[1]);
+            for(PyObject* type : types){
+                vm->check_non_tagged_type(type, vm->tp_type);
+                if(vm->isinstance(args[0], PK_OBJ_GET(Type, type))) return vm->True;
+            }
+            return vm->False;
+        }
         vm->check_non_tagged_type(args[1], vm->tp_type);
         Type type = PK_OBJ_GET(Type, args[1]);
         return VAR(vm->isinstance(args[0], type));

+ 18 - 0
tests/40_class.py

@@ -77,6 +77,24 @@ assert isinstance(d, A)
 assert isinstance(object, object)
 assert isinstance(type, object)
 
+assert isinstance(1, (float, int))
+assert isinstance(1, (float, object))
+assert not isinstance(1, (float, str))
+assert isinstance(object, (int, type, float))
+assert not isinstance(object, (int, float, str))
+
+try:
+    isinstance(1, (1, 2))
+    exit(1)
+except TypeError:
+    pass
+
+try:
+    isinstance(1, 1)
+    exit(1)
+except TypeError:
+    pass
+
 class A:
     a = 1
     b = 2