[Python-Dev] type(obj) vs. obj.__class__

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:

* Should __repr__() for a stdlib class use type(self).__name__ or
self.__class__.__name__?
* Should __reduce__() return type(self) or self.__class__?
* Should copy() use type(self) or self.__class__?

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