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

Steven D'Aprano steve at pearwood.info
Sun Oct 18 01:55:00 EDT 2015


On Sat, Oct 17, 2015 at 03:45:19PM -0600, Eric Snow wrote:
> 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__.  
[...]
> 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__".

I for one would like to see a definitive explanation for when they are 
different, and when you should use one or the other. The only 
obvious example I've seen is the RingBuffer from the Python Cookbook:

http://code.activestate.com/recipes/68429-ring-buffer/



-- 
Steve


More information about the Python-Dev mailing list