Text stringlengths 1 9.41k |
|---|
In addition, Booleans make truth values more explicit. For instance, an infinite
loop can now be coded as while True: instead of the less intuitive while 1:. |
Similarly,
**|**
-----
flags can be initialized more clearly with flag = False. |
We’ll discuss these statements
further in Part III.
Again, though, for all other practical purposes, you can treat True and False as though
they are predefined variables set to integer 1 and 0. |
Most programmers used to preassign
```
True and False to 1 and 0 anyway; the bool type simply makes this standard. Its im
```
plementation can lead to curious results, though. |
Because True is just the integer 1 with
a custom display format, True + 4 yields 5 in Python:
```
>>> type(True)
<class 'bool'>
>>> isinstance(True, int)
True
```
`>>> True == 1` _# Same value_
```
True
```
`>>> True is 1` _# But different object: see the next chapter_
```
False
```
`>>> True or False` _... |
Because numeric programming is a popular domain for Python,
you’ll find a wealth of advanced tools.
For example, if you need to do serious number crunching, an optional extension for
Python called _NumPy (Numeric Python) provides advanced numeric programming_
tools, such as a matrix data type, vector processing, and s... |
Hardcore scientific programming groups at places like Los Alamos and NASA
use Python with NumPy to implement the sorts of tasks they previously coded in
C++, FORTRAN, or Matlab. |
The combination of Python and NumPy is often compared to a free, more flexible version of Matlab—you get NumPy’s performance, plus
the Python language and its libraries.
Because it’s so advanced, we won’t talk further about NumPy in this book. |
You can
find additional support for advanced numeric programming in Python, including
graphics and plotting tools, statistics libraries, and the popular SciPy package at Python’s PyPI site, or by searching the Web. |
Also note that NumPy is currently an optional
extension; it doesn’t come with Python and must be installed separately.
**|**
-----
###### Chapter Summary
This chapter has taken a tour of Python’s numeric object types and the operations we
can apply to them. |
Along the way, we met the standard integer and floating-point types,
as well as some more exotic and less commonly used types such as complex numbers,
fractions, and sets. |
We also explored Python’s expression syntax, type conversions,
bitwise operations, and various literal forms for coding numbers in scripts.
Later in this part of the book, I’ll fill in some details about the next object type, the
string. |
In the next chapter, however, we’ll take some time to explore the mechanics of
variable assignment in more detail than we have here. |
This turns out to be perhaps the
most fundamental idea in Python, so make sure you check out the next chapter before
moving on. |
First, though, it’s time to take the usual chapter quiz.
###### Test Your Knowledge: Quiz
1. What is the value of the expression 2 * (3 + 4) in Python?
2. |
What is the value of the expression 2 * 3 + 4 in Python?
3. What is the value of the expression 2 + 3 * 4 in Python?
4. What tools can you use to find a number’s square root, as well as its square?
5. |
What is the type of the result of the expression 1 + 2.0 + 3?
6. How can you truncate and round a floating-point number?
7. How can you convert an integer to a floating-point number?
8. |
How would you display an integer in octal, hexadecimal, or binary notation?
9. How might you convert an octal, hexadecimal, or binary string to a plain integer?
###### Test Your Knowledge: Answers
1. |
The value will be 14, the result of 2 * 7, because the parentheses force the addition
to happen before the multiplication.
2. The value will be 10, the result of 6 + 4. |
Python’s operator precedence rules are
applied in the absence of parentheses, and multiplication has higher precedence
than (i.e., happens before) addition, per Table 5-2.
3. |
This expression yields 14, the result of 2 + 12, for the same precedence reasons as
in the prior question.
4. |
Functions for obtaining the square root, as well as _pi, tangents, and more, are_
available in the imported math module. To find a number’s square root, import
```
math and call math.sqrt(N). |
To get a number’s square, use either the exponent
```
**|**
-----
expression X ** 2 or the built-in function pow(X, 2). |
Either of these last two can
also compute the square root when given a power of 0.5 (e.g., X ** .5).
5. |
The result will be a floating-point number: the integers are converted up to floating
point, the most complex type in the expression, and floating-point math is used to
evaluate it.
6. |
The int(N) and math.trunc(N) functions truncate, and the round(N, `digits) func-`
tion rounds. |
We can also compute the floor with `math.floor(N) and round for`
display with string formatting operations.
7. |
The float(I) function converts an integer to a floating point; mixing an integer
with a floating point within an expression will result in a conversion as well. |
In
some sense, Python 3.0 / division converts too—it always returns a floating-point
result that includes the remainder, even if both operands are integers.
8. |
The oct(I) and hex(I) built-in functions return the octal and hexadecimal string
forms for an integer. The bin(I) call also returns a number’s binary digits string in
Python 2.6 and 3.0. |
The % string formatting expression and format string method
also provide targets for some such conversions.
9. |
The `int(S,` `base) function can be used to convert from octal and hexadecimal`
strings to normal integers (pass in 8, 16, or 2 for the base). |
The eval(S) function
can be used for this purpose too, but it’s more expensive to run and can have
security issues. |
Note that integers are always stored in binary in computer memory;
these are just display string format conversions.
**|**
-----
###### CHAPTER 6
### The Dynamic Typing Interlude
In the prior chapter, we began exploring Python’s core object types in depth with a
look at Python numbers. |
We’ll resume our object type tour in the next chapter, but
before we move on, it’s important that you get a handle on what may be the most
fundamental idea in Python programming and is certainly the basis of much of both
the conciseness and flexibility of the Python language—dynamic typing, and the polymorphism it yiel... |
In fact, programs should not even care about specific
types; in exchange, they are naturally applicable in more contexts than we can sometimes even plan ahead for. |
Because dynamic typing is the root of this flexibility, let’s
take a brief look at the model here.
###### The Case of the Missing Declaration Statements
If you have a background in compiled or statically typed languages like C, C++, or Java,
you might find yourself a bit perplexed at this point in the book. |
So far, we’ve been
using variables without declaring their existence or their types, and it somehow works.
When we type a = 3 in an interactive session or program file, for instance, how does
Python know that a should stand for an integer? |
For that matter, how does Python
know what a is at all?
Once you start asking such questions, you’ve crossed over into the domain of Python’s
_dynamic typing model. |
In Python, types are determined automatically at runtime, not_
in response to declarations in your code. |
This means that you never declare variables
ahead of time (a concept that is perhaps simpler to grasp if you keep in mind that it all
boils down to variables, objects, and the links between them).
-----
###### Variables, Objects, and References
As you’ve seen in many of the examples used so far in this book, when y... |
In the
Python language, this all pans out in a very natural way, as follows:
_Variable creation_
A variable (i.e., name), like a, is created when your code first assigns it a value.
Future assignments change the value of the already created name. |
Technically,
Python detects some names before your code runs, but you can think of it as though
initial assignments make variables.
_Variable types_
A variable never has any type information or constraints associated with it. |
The
notion of type lives with objects, not names. |
Variables are generic in nature; they
always simply refer to a particular object at a particular point in time.
_Variable use_
When a variable appears in an expression, it is immediately replaced with the object
that it currently refers to, whatever that may be. |
Further, all variables must be
explicitly assigned before they can be used; referencing unassigned variables results
in errors.
In sum, variables are created when assigned, can reference any type of object, and must
be assigned before they are referenced. |
This means that you never need to declare names
used by your script, but you must initialize names before you can update them; counters, for example, must be initialized to zero before you can add to them.
This dynamic typing model is strikingly different from the typing model of traditional
languages. |
When you are first starting out, the model is usually easier to understand if
you keep clear the distinction between names and objects. |
For example, when we say
this:
```
>>> a = 3
```
at least conceptually, Python will perform three distinct steps to carry out the request.
These steps reflect the operation of all assignments in the Python language:
1. |
Create an object to represent the value 3.
2. Create the variable a, if it does not yet exist.
3. |
Link the variable a to the new object 3.
The net result will be a structure inside Python that resembles Figure 6-1. |
As sketched,
variables and objects are stored in different parts of memory and are associated by links
(the link is shown as a pointer in the figure). |
Variables always link to objects and never
to other variables, but larger objects may link to other objects (for instance, a list object
has links to the objects it contains).
**|**
-----
_Figure 6-1. |
Names and objects after running the assignment a = 3. Variable a becomes a reference to_
_the object 3. |
Internally, the variable is really a pointer to the object’s memory space created by running_
_the literal expression 3._
These links from variables to objects are called references in Python—that is, a reference
is a kind of association, implemented as a pointer in memory.[*] Whenever the variables
are later used (i.... |
This is all simpler than the terminology may imply. |
In concrete terms:
- Variables are entries in a system table, with spaces for links to objects.
- Objects are pieces of allocated memory, with enough space to represent the values
for which they stand.
- References are automatically followed pointers from variables to objects.
At least conceptually, each time yo... |
Internally, as an optimization, Python caches and reuses certain kinds of unchangeable objects, such as small integers and strings (each 0 is not really a new piece
of memory—more on this caching behavior later). |
But, from a logical perspective, it
works as though each expression’s result value is a distinct object and each object is a
distinct piece of memory.
Technically speaking, objects have more structure than just enough space to represent
their values. |
Each object also has two standard header fields: a type designator used to
mark the type of the object, and a reference counter used to determine when it’s OK to
reclaim the object. |
To understand how these two header fields factor into the model,
we need to move on.
###### Types Live with Objects, Not Variables
To see how object types come into play, watch what happens if we assign a variable
multiple times:
- Readers with a background in C may find Python references similar to C pointers (memo... |
In
fact, references are implemented as pointers, and they often serve the same roles, especially with objects that
can be changed in-place (more on this later). |
However, because references are always automatically
dereferenced when used, you can never actually do anything useful with a reference itself; this is a feature
that eliminates a vast category of C bugs. |
You can think of Python references as C “void*” pointers, which
are automatically followed whenever used.
**f** **|**
-----
`>>> a = 3` _# It's an integer_
`>>> a = 'spam'` _# Now it's a string_
`>>> a = 1.23` _# Now it's a floating point_
This isn’t typical Python code, but it does work—a starts out as an integer... |
This example tends to
look especially odd to ex-C programmers, as it appears as though the type of a changes
from integer to string when we say a = 'spam'.
However, that’s not really what’s happening. |
In Python, things work more simply.
Names have no types; as stated earlier, types live with objects, not names. In the preceding listing, we’ve simply changed a to reference different objects. |
Because variables
have no type, we haven’t actually changed the type of the variable a; we’ve simply made
the variable reference a different type of object. |
In fact, again, all we can ever say about
a variable in Python is that it references a particular object at a particular point in time.
Objects, on the other hand, know what type they are—each object contains a header
field that tags the object with its type. |
The integer object 3, for example, will contain
the value `3, plus a designator that tells Python that the object is an integer (strictly`
speaking, a pointer to an object called `int, the name of the integer type). |
The type`
designator of the `'spam' string object points to the string type (called` `str) instead.`
Because objects know their types, variables don’t have to.
To recap, types are associated with objects in Python, not with variables. |
In typical
code, a given variable usually will reference just one kind of object. |
Because this isn’t
a requirement, though, you’ll find that Python code tends to be much more flexible
than you may be accustomed to—if you use Python well, your code might work on
many types automatically.
I mentioned that objects have two header fields, a type designator and a reference
counter. |
To understand the latter of these, we need to move on and take a brief look
at what happens at the end of an object’s life.
###### Objects Are Garbage-Collected
In the prior section’s listings, we assigned the variable a to different types of objects in
each assignment. |
But when we reassign a variable, what happens to the value it was
previously referencing? |
For example, after the following statements, what happens to
the object 3?
```
>>> a = 3
>>> a = 'spam'
```
The answer is that in Python, whenever a name is assigned to a new object, the space
held by the prior object is reclaimed (if it is not referenced by any other name or object).
This automatic reclamation of... |
Again, though this is
not really the case, the effect is as though the type of x is changing over time. Remember,
in Python types live with objects, not names. |
Because names are just generic references
to objects, this sort of code works naturally.
Second, notice that references to objects are discarded along the way. |
Each time x is
assigned to a new object, Python reclaims the prior object’s space. |
For instance, when
it is assigned the string 'shrubbery', the object 42 is immediately reclaimed (assuming
it is not referenced anywhere else)—that is, the object’s space is automatically thrown
back into the free space pool, to be reused for a future object.
Internally, Python accomplishes this feat by keeping a coun... |
As soon as (and
exactly when) this counter drops to zero, the object’s memory space is automatically
reclaimed. |
In the preceding listing, we’re assuming that each time x is assigned to a new
object, the prior object’s reference counter drops to zero, causing it to be reclaimed.
The most immediately tangible benefit of garbage collection is that it means you can
use objects liberally without ever needing to free up space in your... |
Python will
clean up unused space for you as your program runs. |
In practice, this eliminates a
substantial amount of bookkeeping code required in lower-level languages such as C
and C++.
Technically speaking, Python’s garbage collection is based mainly upon
_reference counters, as described here; however, it also has a component_
that detects and reclaims objects with _cyclic refe... |
This_
component can be disabled if you’re sure that your code doesn’t create
cycles, but it is enabled by default.
Because references are implemented as pointers, it’s possible for an object to reference itself, or reference another object that does. |
For example, exercise 3 at the end of Part I and its solution in Appendix B show
how to create a cycle by embedding a reference to a list within itself.
The same phenomenon can occur for assignments to attributes of objects created from user-defined classes. |
Though relatively rare, because
the reference counts for such objects never drop to zero, they must be
treated specially.
For more details on Python’s cycle detector, see the documentation for
the gc module in Python’s library manual. |
Also note that this description
of Python’s garbage collector applies to the standard CPython only; Jython and IronPython may use different schemes, though the net effect
in all is similar—unused space is reclaimed for you automatically.
**f** **|**
-----
###### Shared References
So far, we’ve seen what happens as... |
The second
line causes Python to create the variable b; the variable a is being used and not assigned
here, so it is replaced with the object it references (3), and b is made to reference that
object. |
The net effect is that the variables a and b wind up referencing the same object
(that is, pointing to the same chunk of memory). |
This scenario, with multiple names
referencing the same object, is called a shared reference in Python.
_Figure 6-2. Names and objects after next running the assignment b = a. |
Variable b becomes a reference_
_to the object 3. |
Internally, the variable is really a pointer to the object’s memory space created by_
_running the literal expression 3._
Next, suppose we extend the session with one more statement:
```
>>> a = 3
>>> b = a
>>> a = 'spam'
```
As with all Python assignments, this statement simply makes a new object to represent
... |
It does not, however,
change the value of b; b still references the original object, the integer 3. |
The resulting
reference structure is shown in Figure 6-3.
The same sort of thing would happen if we changed b to 'spam' instead—the assignment
would change only b, not a. |
This behavior also occurs if there are no type differences
at all. For example, consider these three statements:
```
>>> a = 3
>>> b = a
>>> a = a + 2
```
**|**
-----
_Figure 6-3. |
Names and objects after finally running the assignment a = ‘spam’. |
Variable a references_
_the new object (i.e., piece of memory) created by running the literal expression ‘spam’, but variable b_
_still refers to the original object 3. |
Because this assignment is not an in-place change to the object 3,_
_it changes only variable a, not b._
In this sequence, the same events transpire. |
Python makes the variable a reference the
object 3 and makes b reference the same object as a, as in Figure 6-2; as before, the last
assignment then sets a to a completely different object (in this case, the integer 5, which
is the result of the + expression). |
It does not change b as a side effect. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.