Text stringlengths 1 9.41k |
|---|
pdb also includes a postmortem function you can run after an exception
occurs, to get information from the time of the error. |
See the Python library manual
and Chapter 35 for more details on pdb.
- Other options. |
For more specific debugging requirements, you can find additional
tools in the open source domain, including support for multithreaded programs,
embedded code, and process attachment. |
The Winpdb system, for example, is a
**|**
-----
###### Chapter Summary
In this chapter, we’ve looked at common ways to launch Python programs: by running
code typed interactively, and by running code stored in files with system command
lines, file-icon clicks, module imports, exec calls, and IDE GUIs such as IDLE... |
We’ve
covered a lot of pragmatic startup territory here. |
This chapter’s goal was to equip you
with enough information to enable you to start writing some code, which you’ll do in
the next part of the book. |
There, we will start exploring the Python language itself,
beginning with its core data types.
First, though, take the usual chapter quiz to exercise what you’ve learned here. |
Because
this is the last chapter in this part of the book, it’s followed with a set of more complete
exercises that test your mastery of this entire part’s topics. |
For help with the latter set
of problems, or just for a refresher, be sure to turn to Appendix B after you’ve given
the exercises a try.
###### Test Your Knowledge: Quiz
1. |
How can you start an interactive interpreter session?
2. Where do you type a system command line to launch a script file?
3. Name four or more ways to run the code saved in a script file.
4. |
Name two pitfalls related to clicking file icons on Windows.
5. Why might you need to reload a module?
6. How do you run a script from within IDLE?
7. Name two pitfalls related to using IDLE.
8. |
What is a namespace, and how does it relate to module files?
**|**
-----
###### Test Your Knowledge: Answers
1. |
You can start an interactive session on Windows by clicking your Start button,
picking the All Programs option, clicking the Python entry, and selecting the “Python (command line)” menu option. |
You can also achieve the same effect on Windows and other platforms by typing `python as a system command line in your`
system’s console window (a Command Prompt window on Windows). |
Another
alternative is to launch IDLE, as its main Python shell window is an interactive
session. |
If you have not set your system’s PATH variable to find Python, you may
need to cd to where Python is installed, or type its full directory path instead of just
```
python (e.g., C:\Python30\python on Windows).
```
2. |
You type system command lines in whatever your platform provides as a system
console: a Command Prompt window on Windows; an xterm or terminal window
on Unix, Linux, and Mac OS X; and so on.
3. |
Code in a script (really, module) file can be run with system command lines, file
icon clicks, imports and reloads, the exec built-in function, and IDE GUI selections
such as IDLE’s Run→Run Module menu option. |
On Unix, they can also be run as
executables with the #! trick, and some platforms support more specialized launching techniques (e.g., drag-and-drop). |
In addition, some text editors have unique
ways to run Python code, some Python programs are provided as standalone “frozen binary” executables, and some systems use Python code in embedded mode,
where it is run automatically by an enclosing program written in a language like
C, C++, or Java. |
The latter technique is usually done to provide a user customization layer.
4. |
Scripts that print and then exit cause the output file to disappear immediately,
before you can view the output (which is why the input trick comes in handy);
error messages generated by your script also appear in an output window that
closes before you can examine its contents (which is one reason that system command ... |
Python only imports (loads) a module once per process, by default, so if you’ve
changed its source code and want to run the new version without stopping and
restarting Python, you’ll have to reload it. |
You must import a module at least once
before you can reload it. |
Running files of code from a system shell command line,
via an icon click, or via an IDE such as IDLE generally makes this a nonissue, as
those launch schemes usually run the current version of the source code file each
time.
6. |
Within the text edit window of the file you wish to run, select the window’s
Run→Run Module menu option. |
This runs the window’s source code as a top-level
script file and displays its output back in the interactive Python shell window.
7. |
IDLE can still be hung by some types of programs—especially GUI programs that
perform multithreading (an advanced technique beyond this book’s scope). |
Also,
IDLE has some usability features that can burn you once you leave the IDLE GUI:
**|**
-----
a script’s variables are automatically imported to the interactive scope in IDLE, for
instance, but not by Python in general.
8. |
A namespace is just a package of variables (i.e., names). It takes the form of an
object with attributes in Python. |
Each module file is automatically a namespace—
that is, a package of variables reflecting the assignments made at the top level of
the file. |
Namespaces help avoid name collisions in Python programs: because each
module file is a self-contained namespace, files must explicitly import other files
in order to use their names.
###### Test Your Knowledge: Part I Exercises
It’s time to start doing a little coding on your own. |
This first exercise session is fairly
simple, but a few of these questions hint at topics to come in later chapters. |
Be sure to
check “Part I, Getting Started” on page 1101 in the solutions appendix (Appendix B)
for the answers; the exercises and their solutions sometimes contain supplemental information not discussed in the main text, so you should take a peek at the solutions
even if you manage to answer all the questions on your o... |
Interaction. Using a system command line, IDLE, or another method, start the
Python interactive command line (>>> prompt), and type the expression `"Hello`
```
World!" (including the quotes). |
The string should be echoed back to you. The
```
purpose of this exercise is to get your environment configured to run Python. |
In
some scenarios, you may need to first run a cd shell command, type the full path
to the Python executable, or add its path to your `PATH environment variable. |
If`
desired, you can set PATH in your .cshrc or .kshrc file to make Python permanently
available on Unix systems; on Windows, use a setup.bat, autoexec.bat, or the environment variable GUI. |
See Appendix A for help with environment variable
settings.
2. Programs. |
With the text editor of your choice, write a simple module file containing
the single statement `print('Hello module world!') and store it as` _module1.py._
Now, run this file by using any launch option you like: running it in IDLE, clicking
on its file icon, passing it to the Python interpreter on the system shell’s c... |
Which technique seems easiest? (There is no
right answer to this, of course.)
3. Modules. Start the Python interactive command line (>>> prompt) and import the
module you wrote in exercise 2. |
Try moving the file to a different directory and
importing it again from its original directory (i.e., run Python in the original directory when you import). What happens? |
(Hint: is there still a module1.pyc byte
code file in the original directory?)
**|**
-----
4. Scripts. If your platform supports it, add the `#! |
line to the top of your`
_module1.py module file, give the file executable privileges, and run it directly as an_
executable. What does the first line need to contain? #! |
usually only has meaning
on Unix, Linux, and Unix-like platforms such as Mac OS X; if you’re working on
Windows, instead try running your file by listing just its name in a DOS console
window without the word “python” before it (this works on recent versions of
Windows), or via the Start→Run... |
dialog box.
5. Errors and debugging. Experiment with typing mathematical expressions and assignments at the Python interactive command line. |
Along the way, type the expressions 2 ** 500 and 1 / 0, and reference an undefined variable name as we did
in this chapter. |
What happens?
You may not know it yet, but when you make a mistake, you’re doing exception
processing (a topic we’ll explore in depth in Part VII). |
As you’ll learn there, you
are technically triggering what’s known as the default exception handler—logic that
prints a standard error message. |
If you do not catch an error, the default handler
does and prints the standard error message in response.
Exceptions are also bound up with the notion of debugging in Python. |
When you’re
first starting out, Python’s default error messages on exceptions will probably provide as much error-handling support as you need—they give the cause of the error,
as well as showing the lines in your code that were active when the error occurred.
For more about debugging, see the sidebar “Debugging Python... |
Breaks and cycles. |
At the Python command line, type:
```
L = [1, 2] # Make a 2-item list
L.append(L) # Append L as a single item to itself
L # Print L
```
What happens? |
In all recent versions of Python, you’ll see a strange output that
we’ll describe in the solutions appendix, and which will make more sense when
we study references in the next part of the book. |
If you’re using a Python version
older than 1.5.1, a Ctrl-C key combination will probably help on most platforms.
Why do you think your version of Python responds the way it does for this code?
If you do have a Python older than Release 1.5.1 (a hopefully rare
scenario today!), make sure your machine can stop a progra... |
Documentation. |
Spend at least 17 minutes browsing the Python library and language manuals before moving on to get a feel for the available tools in the standard
library and the structure of the documentation set. |
It takes at least this long to
become familiar with the locations of major topics in the manual set; once you’ve
done this, it’s easy to find what you need. |
You can find this manual via the Python
**|**
-----
Start button entry on Windows, in the Python Docs option on the Help pull-down
menu in IDLE, or online at http://www.python.org/doc. |
I’ll also have a few more
words to say about the manuals and other documentation sources available (including PyDoc and the `help function) in` Chapter 15. |
If you still have time, go
explore the Python website, as well as its PyPy third-party extension repository.
Especially check out the Python.org documentation and search pages; they can be
crucial resources.
**|**
-----
##### PART II
## Types and Operations
-----
-----
###### CHAPTER 4
### Introducing Python O... |
In an informal sense, in Python,
we do things with stuff. “Things” take the form of operations like addition and concatenation, and “stuff” refers to the objects on which we perform those operations. |
In
this part of the book, our focus is on that stuff, and the things our programs can do
with it.
Somewhat more formally, in Python, data takes the form of objects—either built-in
objects that Python provides, or objects we create using Python or external language
tools such as C extension libraries. |
Although we’ll firm up this definition later, objects
are essentially just pieces of memory, with values and sets of associated operations.
Because objects are the most fundamental notion in Python programming, we’ll start
this chapter with a survey of Python’s built-in object types.
By way of introduction, however, ... |
From a more concrete perspective, Python programs
can be decomposed into modules, statements, expressions, and objects, as follows:
1. Programs are composed of modules.
2. |
Modules contain statements.
3. Statements contain expressions.
4. |
Expressions create and process objects.
The discussion of modules in Chapter 3 introduced the highest level of this hierarchy.
This part’s chapters begin at the bottom, exploring both built-in objects and the expressions you can code to use them.
-----
###### Why Use Built-in Types?
If you’ve used lower-level lang... |
You need to lay out memory structures,
manage memory allocation, implement search and access routines, and so on. |
These
chores are about as tedious (and error-prone) as they sound, and they usually distract
from your program’s real goals.
In typical Python programs, most of this grunt work goes away. |
Because Python provides powerful object types as an intrinsic part of the language, there’s usually no need
to code object implementations before you start solving problems. |
In fact, unless you
have a need for special processing that built-in types don’t provide, you’re almost always better off using a built-in object instead of implementing your own. |
Here are some
reasons why:
- Built-in objects make programs easy to write. For simple tasks, built-in types
are often all you need to represent the structure of problem domains. |
Because you
get powerful tools such as collections (lists) and search tables (dictionaries) for free,
you can use them immediately. |
You can get a lot of work done with Python’s builtin object types alone.
- Built-in objects are components of extensions. |
For more complex tasks, you
may need to provide your own objects using Python classes or C language interfaces. |
But as you’ll see in later parts of this book, objects implemented manually
are often built on top of built-in types such as lists and dictionaries. |
For instance,
a stack data structure may be implemented as a class that manages or customizes
a built-in list.
- Built-in objects are often more efficient than custom data structures. |
Python’s built-in types employ already optimized data structure algorithms that are
implemented in C for speed. |
Although you can write similar object types on your
own, you’ll usually be hard-pressed to get the level of performance built-in object
types provide.
- Built-in objects are a standard part of the language. |
In some ways, Python
borrows both from languages that rely on built-in tools (e.g., LISP) and languages
that rely on the programmer to provide tool implementations or frameworks of
their own (e.g., C++). |
Although you can implement unique object types in Python,
you don’t need to do so just to get started. |
Moreover, because Python’s built-ins
are standard, they’re always the same; proprietary frameworks, on the other hand,
tend to differ from site to site.
In other words, not only do built-in object types make programming easier, but they’re
also more powerful and efficient than most of what can be created from scratch. |
Regardless of whether you implement new object types, built-in objects form the core of
every Python program.
**|**
-----
###### Python’s Core Data Types
Table 4-1 previews Python’s built-in object types and some of the syntax used to code
their literals—that is, the expressions that generate these objects.[*] Som... |
Built-in objects preview_
**Object type** **Example literals/creation**
Numbers `1234, 3.1415, 3+4j, Decimal, Fraction`
Strings `'spam', "guido's", b'a\x01c'`
Lists `[1, [2, 'three'], 4]`
Dictionaries `{'food': 'spam', 'taste': 'yum'}`
Tuples `(1, 'spam', 4, 'U')`
Files `myfile = open('eggs', 'r')`
Sets `set(... |
For instance, when we perform text pattern matching in Python, we
create pattern objects, and when we perform network scripting, we use socket objects.
These other kinds of objects are generally created by importing and using modules and
have behavior all their own.
As we’ll see in later parts of the book, program uni... |
Python also provides a set of implementation-related
types such as compiled code objects, which are generally of interest to tool builders
more than application developers; these are also discussed in later parts of this text.
We usually call the other object types in Table 4-1 _core data types, though, because_
they ... |
For instance, when you run the following code:
```
>>> 'spam'
```
- In this book, the term literal simply means an expression whose syntax generates an object—sometimes also
called a constant. |
Note that the term “constant” does not imply objects or variables that can never be changed
(i.e., this term is unrelated to C++’s `const or Python’s “immutable”—a topic explored in the section`
“Immutability” on page 82).
**|**
-----
you are, technically speaking, running a literal expression that generates and re... |
There is specific Python language syntax to make this object. Similarly, an expression wrapped in square brackets makes a list, one in curly braces makes
a dictionary, and so on. |
Even though, as we’ll see, there are no type declarations in
Python, the syntax of the expressions you run determines the types of objects you create
and use. |
In fact, object-generation expressions like those in Table 4-1 are generally
where types originate in the Python language.
Just as importantly, once you create an object, you bind its operation set for all time—
you can perform only string operations on a string and list operations on a list. |
As you’ll
learn, Python is dynamically typed (it keeps track of types for you automatically instead
of requiring declaration code), but it is also strongly typed (you can perform on an object
only operations that are valid for its type).
Functionally, the object types in Table 4-1 are more general and powerful than wh... |
For instance, you’ll find that lists and dictionaries alone
are powerful data representation tools that obviate most of the work you do to support
collections and searching in lower-level languages. |
In short, lists provide ordered collections of other objects, while dictionaries store objects by key; both lists and dictionaries may be nested, can grow and shrink on demand, and may contain objects of
any type.
We’ll study each of the object types in Table 4-1 in detail in upcoming chapters. |
Before
digging into the details, though, let’s begin by taking a quick look at Python’s core
objects in action. |
The rest of this chapter provides a preview of the operations we’ll
explore in more depth in the chapters that follow. |
Don’t expect to find the full story
here—the goal of this chapter is just to whet your appetite and introduce some key
ideas. |
Still, the best way to get started is to get started, so let’s jump right into some
real code.
###### Numbers
If you’ve done any programming or scripting in the past, some of the object types in
Table 4-1 will probably seem familiar. |
Even if you haven’t, numbers are fairly straightforward. |
Python’s core objects set includes the usual suspects: integers (numbers without a fractional part), floating-point numbers (roughly, numbers with a decimal point
in them), and more exotic numeric types (complex numbers with imaginary parts,
fixed-precision decimals, rational fractions with numerator and denominator, a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.