Type of an object: ‘obj.__class__’ versus ‘type(obj)’

Ned Batchelder ned at nedbatchelder.com
Sun Dec 15 21:50:23 EST 2013


On 12/15/13 8:51 PM, Ben Finney wrote:
> Howdy all,
>
> What is the Pythonic way to determine the type of an object? Are there
> multiple valid ways, and when should each be used?
>
> We have ‘obj.__class__’, an attribute bound to the object's class. Or is
> it? When is that true, and when should we not rely on it?
>
> We have ‘type(obj)’, calling the constructor for the ‘type’ type in
> order to get a reference to the type of ‘obj’. Or is it? When is that
> true, and when should we not rely on it?
>
> Are there other ways to get at the type of a Python object? What reasons
> are there to choose or avoid them?
>

Generally, my answer would be, "You probably don't need the type as much 
as you think you do."   But when you do need it, type(x) is better than 
x.__class__, simply because we should always favor builtin functions 
over direct access of dunder-names where possible.

Also, don't overlook isinstance().

-- 
Ned Batchelder, http://nedbatchelder.com




More information about the Python-list mailing list