-3

When I do this:

>>> 1 is int
False

It returns False, even when I would expect it to return True. The same behavior occurs when attempting to type-check a variable.

>>> a = 1
>>> a is int
False

I understand that this has something to do with using is instead of isinstance or type.

>>> type(1)
<class 'int'>
>>> isinstance(1, int)
True
>>> type(1) is int
True

Could someone explain exactly why using is does not work in this case? It makes sense to me semantically that it would return True instead of False.

Remolten
  • 2,614
  • 2
  • 25
  • 29

1 Answers1

3

1 is an int, int is a type.

They can't be equal or be the same object, so is is always False between those two (is checks if the objects are actually the same object).

So this is a question of misinterpreting what is checks. The correct way indeed is to use isinstance like you did.

user2357112
  • 260,549
  • 28
  • 431
  • 505
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
  • Understood. My issue is that it makes sense *semantically* for `1 is int` to be `True`, yet it isn't. – Remolten Apr 27 '17 at 17:42
  • yes, natural language vs python ;) same issue with the classical: `if a == 1 or 2:` that we see each week – Jean-François Fabre Apr 27 '17 at 17:46
  • 1
    @Remolten: It makes sense with the semantics of the English word "is", but not with the semantics of the Python operator `is`. – user2357112 Apr 27 '17 at 17:46
  • 1
    @Jean-FrançoisFabre: `==` doesn't start with a reference comparison (that's the final fallback), and it doesn't involve a type comparison. You can have stuff like `x = float('nan'); x != x`, where the same object compares unequal to itself, or `1 == 1.0`, where objects of different type compare equal. – user2357112 Apr 27 '17 at 17:54
  • @user2357112 totally! you're right. I'll delete my comment. but how can references be equal (final fallback) if the values are different? damn the `x = float('nan')` example is good!! – Jean-François Fabre Apr 27 '17 at 17:58