[Tutor] isinstance versus 'is'?
Steven D'Aprano
steve at pearwood.info
Tue Jul 5 20:54:42 EDT 2016
On Tue, Jul 05, 2016 at 03:05:45PM -0400, Alex Hall wrote:
> >>> a = 5
> >>> isinstance(a, int)
> True
> >>> a is int
> False
>
> What happened there? Don't these do the same thing? I thought I could use
> them interchangeably?
You're probably thinking of "is a", as in, "5 is an int", "'Hello
World' is a str", "[1, 2, 3] is a list", etc.
Python doesn't have an operator for testing "is a" relationships, it
uses isinstance(obj, type). There's also issubclass(), for testing
whether one class is a subclass of another.
"x is y" checks whether the two operands x and y are the same object.
That's *not* the same as checking whether they are equal. You should
hardly ever use "is" in Python, with the exception of testing for None:
"if obj is None: ..." sort of thing.
--
Steve
More information about the Tutor
mailing list