15.04.2013 Views

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

4.5.3. Boolean<br />

In the above examples with the foo1 and foo2 objects, you will notice<br />

that we use floating point values rather than integers. The reason for<br />

this is although integers and strings are immutable objects, <strong>Python</strong><br />

sometimes caches them to be more efficient. This would have caused<br />

the examples to appear that <strong>Python</strong> is not creating a new object when<br />

it should have. For example:<br />

>>> a = 1<br />

>>> id(a)<br />

8402824<br />

>>> b = 1<br />

>>> id(b)<br />

8402824<br />

>>><br />

>>> c = 1.0<br />

>>> id(c)<br />

8651220<br />

>>> d = 1.0<br />

>>> id(d)<br />

8651204<br />

In the above example, a and b reference the same integer object, but<br />

c and d do not reference the same float object. If we were purists, we<br />

would want a and b to work just like c and d because we really did ask<br />

to create a new integer object rather than an alias, as in b = a.<br />

<strong>Python</strong> caches or interns only simple integers that it believes will be<br />

used frequently in any <strong>Python</strong> application. At the time of this writing,<br />

<strong>Python</strong> interns integers in the range(-1, 100) but this is subject to<br />

change, so do not code your application to expect this.<br />

In <strong>Python</strong> 2.3, the decision was made to no longer intern strings that<br />

do not have at least one reference outside of the "interned strings<br />

table." This means that without that reference, interned strings are no<br />

longer immortal and subject to garbage collection like everything else.<br />

A BIF introduced in 1.5 to request interning of strings, intern(), has<br />

now been deprecated as a result.<br />

Expressions may be linked together or negated using the Boolean logical operators and, or, and not, all<br />

of which are <strong>Python</strong> keywords. These Boolean operations are in highest-to-lowest order of precedence in<br />

Table 4.3. The not operator has the highest precedence and is immediately one level below all the<br />

comparison operators. The and and or operators follow, respectively.

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

Saved successfully!

Ooh no, something went wrong!