12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Because <strong>Python</strong> caches and reuses small integers and small strings, as mentioned earlier,the object 42 here is probably not literally reclaimed; instead, it will likely remainin a system table to be reused the next time you generate a 42 in your code. Mostkinds of objects, though, are reclaimed immediately when no longer referenced; forthose that are not, the caching mechanism is irrelevant to your code.For instance, because of <strong>Python</strong>’s reference model, there are two different ways tocheck for equality in a <strong>Python</strong> program. Let’s create a shared reference to demonstrate:>>> L = [1, 2, 3]>>> M = L # M and L reference the same object>>> L == M # Same valueTrue>>> L is M # Same objectTrueThe first technique here, the == operator, tests whether the two referenced objectshave the same values; this is the method almost always used for equality checks in<strong>Python</strong>. The second method, the is operator, instead tests for object identity—itreturns True only if both names point to the exact same object, and so is a muchstronger form of equality testing.Really, is simply compares the pointers that implement references, and is a way todetect shared references in your code if needed. It returns False if the names point toequivalent but different objects, as is the case when we run two different literalexpressions:>>> L = [1, 2, 3]>>> M = [1, 2, 3] # M and L reference different objects>>> L == M # Same valuesTrue>>> L is M # Different objectsFalseWatch what happens when we perform the same operations on small numbers:>>> X = 42>>> Y = 42 # Should be two different objects>>> X == YTrue>>> X is Y # Same object anyhow: caching at work!TrueIn this interaction, X and Y should be == (same value), but not is (same object)because we ran two different literal expressions. Because small integers and stringsare cached and reused, though, is tells us they reference the same single object.In fact, if you really want a look under the hood, you can always ask <strong>Python</strong> howmany references there are to an object: the getrefcount function in the standard sysmodule returns the object’s reference count. When I ask about the integer object 1 inthe IDLE GUI, for instance, it reports 837 reuses of this same object (most of whichare in IDLE’s system code, not mine):120 | Chapter 6: The Dynamic Typing Interlude

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!