‹ All Python questions

Python Practice Question 2: Identity vs Equality

Python · Test 1 · question 2 of 10

Data Model & Identitymedium

A billing check does if billed_count is expected_count: where both values are integers computed at runtime. Unit tests with counts like 5 and 42 always pass, but in production, where counts are in the thousands, the check sometimes reports a mismatch even though logging shows both values are the same number. What is the most likely explanation?

Select one answer
Show answer and explanation

Answer:

  • C. is tests object identity; CPython reuses cached objects for small integers, but equal larger integers can be distinct objects, so the check should use ==

x is y is true only when x and y are the same object. As a CPython implementation detail, the interpreter keeps preallocated objects for every integer from -5 to 256, so any computation that produces 42 hands back the same cached object, which is why the tests pass by accident. Larger values produced at runtime are usually new objects: a = 1000; b = int('1000'); print(a == b, a is b) prints True False. Value comparison must use ==; is is for singletons such as None. (Since 3.8, CPython even emits a SyntaxWarning when you write is against an int literal.)

Option A is wrong: Python 3 has a single int type with arbitrary precision. Nothing switches types at 256; that boundary is only the edge of the small-integer cache.

Option B is wrong: is does not use hashes at all, and hash randomization applies to str and bytes, not integers; hash(1000) is 1000 in every process.

Option D is wrong: is never falls back to value equality, for any type. The values really are equal, as the logs show; the objects are different.

References: Programming FAQ: When can I rely on identity tests with the is operator?; C API: PyLong_FromLong (small integer cache)

Practice Test 1 ›