I've seen people often recommend using isinstance() instead of type(), which I find odd because type() seems more readable to me.
>>> isinstance("String",str)
True
>>> type("String") is str
True
The latter seems more pythonic and clear while the former is slightly obfuscated and implies a specific use to me (for example, testing user built classes rather than built in types) but is there some other benefit that I'm unaware of? Does type() cause some erratic behaviour or miss some comparisons?
Answer
Let me give you a simple example why they can be different:
>>> class A(object): pass
>>> class B(A) : pass
>>> a = A()
>>> b = B()
So far, declared a variable A
and a variable B
derived from A
.
>>> isinstance(a, A)
True
>>> type(a) == A
True
BUT
>>> isinstance(b, A)
True
>>> type(b) == A
False
No comments:
Post a Comment