Is there something like python issubclass that will return False if the first arg is not a class?

I would like issubclass(1, str) return false, 1 not a subclass of str . Since this is not a class, I get a TypeError.

Is there a good way to test this without resorting to try, except ?

 try: if issubclass(value, MyClass): do_stuff() except TypeError: pass 
+2
source share
4 answers
 import inspect def isclassandsubclass(value, classinfo): return inspect.isclass(value) and issubclass(value, classinfo) 
+2
source

It seems to you that you want:

 >>> isinstance(1, str) False 
+3
source

Not sure if your file is usecase, but it checks the class or class instance, things are too different (and have different API methods: issubclass () vs. isinstance ()).

Therefore, you always need to check if your "element" is an instance of something of a class.

<P →
 >> (1).__class__ <type 'int'> >>> (1).__class__.__class__ <type 'type'> 
0
source

you can just check before issubclass() :

 import types def myissubclass (c, sc): if type(c) != types.ClassType return False return issubclass (c, sc) 

but I think it would be more pythonic to accept exceptions:

 def myissubclass (c, sc): try: return issubclass (c, sc) except TypeError: return False 
0
source

Source: https://habr.com/ru/post/1388788/


All Articles