Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell the difference between a user-defined class and a built-in in Python 3?

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?

like image 234
Bee Avatar asked Sep 16 '25 16:09

Bee


1 Answers

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.

like image 183
Draconis Avatar answered Sep 19 '25 06:09

Draconis