@@ -44,7 +44,7 @@ func init() {
44
44
// py.MustNewMethod("hex", builtin_hex, 0, hex_doc),
45
45
// py.MustNewMethod("id", builtin_id, 0, id_doc),
46
46
// py.MustNewMethod("input", builtin_input, 0, input_doc),
47
- // py.MustNewMethod("isinstance", builtin_isinstance, 0, isinstance_doc),
47
+ py .MustNewMethod ("isinstance" , builtin_isinstance , 0 , isinstance_doc ),
48
48
// py.MustNewMethod("issubclass", builtin_issubclass, 0, issubclass_doc),
49
49
py .MustNewMethod ("iter" , builtin_iter , 0 , iter_doc ),
50
50
py .MustNewMethod ("len" , builtin_len , 0 , len_doc ),
@@ -826,6 +826,45 @@ object.
826
826
The globals and locals are dictionaries, defaulting to the current
827
827
globals and locals. If only globals is given, locals defaults to it.`
828
828
829
+ const isinstance_doc = `isinstance(obj, class_or_tuple) -> bool
830
+
831
+ Return whether an object is an instance of a class or of a subclass thereof.
832
+
833
+ A tuple, as in isinstance(x, (A, B, ...)), may be given as the target to
834
+ check against. This is equivalent to isinstance(x, A) or isinstance(x, B)
835
+ or ... etc.
836
+ `
837
+
838
+ func isinstance (obj py.Object , classOrTuple py.Object ) (py.Bool , error ) {
839
+ switch classOrTuple .(type ) {
840
+ case py.Tuple :
841
+ var class_tuple = classOrTuple .(py.Tuple )
842
+ for idx := range class_tuple {
843
+ res , _ := isinstance (obj , class_tuple [idx ])
844
+ if res {
845
+ return res , nil
846
+ }
847
+ }
848
+ return false , nil
849
+ default :
850
+ if classOrTuple .Type ().ObjectType != py .TypeType {
851
+ return false , py .ExceptionNewf (py .TypeError , "isinstance() arg 2 must be a type or tuple of types" )
852
+ }
853
+ return obj .Type () == classOrTuple , nil
854
+ }
855
+ }
856
+
857
+ func builtin_isinstance (self py.Object , args py.Tuple ) (py.Object , error ) {
858
+ var obj py.Object
859
+ var classOrTuple py.Object
860
+ err := py .UnpackTuple (args , nil , "isinstance" , 2 , 2 , & obj , & classOrTuple )
861
+ if err != nil {
862
+ return nil , err
863
+ }
864
+
865
+ return isinstance (obj , classOrTuple )
866
+ }
867
+
829
868
const iter_doc = `iter(iterable) -> iterator
830
869
iter(callable, sentinel) -> iterator
831
870
0 commit comments