What happened to types.ClassType in python 3?
Asked Answered
L

2

19

I have a script where I do some magic stuff to dynamically load a module, and instantiate the first class found in the module. But I can't use types.ClassType anymore in Python 3. What is the correct way to do this now?

Lenes answered 9/2, 2009 at 18:19 Comment(0)
L
25

I figured it out. It seems that classes are of type "type". Here is an example of how to distinguish between classes and other objects at runtime.

>>> class C: pass
... 
>>> type(C)
<class 'type'>
>>> isinstance(C, type)
True
>>> isinstance('string', type)
False
Lenes answered 9/2, 2009 at 18:38 Comment(1)
Thanks! I tried using type(C) is type, which worked for simple classes, but not when C uses a metaclass. isinstance(C, type), as you wrote, still returns True in that case, however.Hilaire
N
6

It was used for classic classes. In Python 3 they're gone. I suppose you could use something like:

issubclass(ClassName, object)
Nel answered 9/2, 2009 at 18:30 Comment(1)
This will throw if the ClassName variable happens to be not a class type. For example issubclass('hello', object) will throw.Thorncombe

© 2022 - 2024 — McMap. All rights reserved.