[Python-Dev] type(obj) vs. obj.class (original) (raw)

Eric Snow ericsnowcurrently at gmail.com
Sat Oct 17 17:45:19 EDT 2015


In a recent tracker issue about OrderedDict [1] we've had some discussion about the use of type(od) as a replacement for od.class. It came up because the pure Python implementation of OrderedDict uses self.class in 3 different methods (repr, reduce, and copy). The patch in that issue changes the C implementation to use Py_TYPE(). [2] So I wanted to get some feedback on the practical implications of such a change and if we need to clarify the difference more formally.

In this specific case [3] there are 3 questions:

The more general question of when we use type(obj) vs. obj.class applies to both the language and to all the stdlib as I expect consistency there would result in fewer surprises. I realize that there are some places where using obj.class makes more sense (e.g. for some proxy support). There are other places where using type(obj) is the way to go (e.g. special method lookup). However, the difference is muddled enough that usage is inconsistent in the stdlib. For example, C-implemented types use Py_TYPE() almost exclusively.

So, would it make sense to establish some concrete guidelines about when to use type(obj) vs. obj.class? If so, what would those be? It may also be helpful to enumerate use cases for "type(obj) is not obj.class".

-eric

[1] http://bugs.python.org/issue25410 [2] I'm going to open a separate thread about the issue of compatibility and C accelerated types. [3] https://hg.python.org/cpython/file/default/Lib/collections/init.py#l238



More information about the Python-Dev mailing list