@@ -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,50 @@ 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 (args py.Tuple ) (py.Bool , error ) {
839
+ switch args [1 ].(type ) {
840
+ case py.Tuple :
841
+ {
842
+ var res py.Bool
843
+ var class = args [1 ].(py.Tuple )
844
+ for idx := range class {
845
+ var new_args []py.Object
846
+ new_args = append (new_args , args [0 ], class [idx ])
847
+ temp , err := isinstance (new_args )
848
+ if err != nil {
849
+ return false , err
850
+ }
851
+ res = res || temp
852
+ }
853
+ return res , nil
854
+ }
855
+ default :
856
+ {
857
+ if args [0 ].Type () != py .TypeType {
858
+ return false , py .ExceptionNewf (py .TypeError , "isinstance() arg 2 must be a type or tuple of types" )
859
+ }
860
+ return args [0 ].Type () == args [1 ], nil
861
+ }
862
+ }
863
+ }
864
+
865
+ func builtin_isinstance (self py.Object , args py.Tuple ) (py.Object , error ) {
866
+ if len (args ) > 2 {
867
+ return nil , py .ExceptionNewf (py .TypeError , "isinstance expected 2 arguments, got %d" , len (args ))
868
+ }
869
+
870
+ return isinstance (args )
871
+ }
872
+
829
873
const iter_doc = `iter(iterable) -> iterator
830
874
iter(callable, sentinel) -> iterator
831
875
0 commit comments