I am porting some Python 2 code to 3. There is a section that relies on knowing if an object is an instance of a user-defined class, or a built-in. The Python 2 code used:
isinstance(my_object.__class__, Types.ClassType)
python modernize recommends changing "Types.ClassType" to "type". That doesn't work for me because all objects are returning true, we are a "type". From what I understand about classes and Python 3, there is not a difference anymore between built-ins and user-defined classes. I have done almost a full day of research and am getting nowhere. I can't believe I'm the only person in this situation, but maybe I'm not searching the right phrases....
So my question is, is it possible to tell the difference, or do I need to refactor the code so it won't matter?
Check the __module__
attribute of the type. That tells you where the type was defined.
>>> class Test: pass
...
>>> a = 42
>>> b = Test()
>>> type(a).__module__
'builtins'
>>> type(b).__module__
'__main__'
When classes from other modules are involved it's a bit less trivial, but that was true in Python 2 as well.
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