Question

I recently saw this code:

x = [2, 3, 4]
if type(x) is list:
    #some logic

and was confused how the if condition went off...I thought that is checks for memory identity and the id of x is different from the id of list, but if that's the case how did this if condition even go off? (I was under the impression that the only native singleton in Python was None).

Was it helpful?

Solution

Here x is an instance of class list, in new style classes type() returns the class of the instance itself, i.e list in this case. Consider this simple example:

>>> class A(object):
    pass
... 
>>> type(A())         #calling type on the instance returns its class
<class '__main__.A'>
>>> type(A()) is A
True

Note that the above example will not work for user defined old-style classes as all the instances there were of type instance.

>>> class A:
    pass
... 
>>> type(A())
<type 'instance'>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top