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?
Syntax of the Python type() function The type() function is used to get the type of an object. Python type() function syntax is: type(object) type(name, bases, dict) When a single argument is passed to the type() function, it returns the type of the object. Its value is the same as the object.
If you need to check the type of an object, it is recommended to use the Python isinstance() function instead. It's because isinstance() function also checks if the given object is an instance of the subclass.
The types module contains type objects for all object types defined by the standard interpreter, as Example 1-86 demonstrates. All objects of the same type share a single type object. You can use is to test if an object has a given type.
To get the type of a variable in Python, you can use the built-in type() function. In Python, everything is an object. So, when you use the type() function to print the type of the value stored in a variable to the console, it returns the class type of the object.
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
It was used for classic classes. In Python 3 they're gone. I suppose you could use something like:
issubclass(ClassName, object)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With