!= (not equal to) operator, 580
# sign, comments, 116
adding pound bang line, 329
% character, string formatting, 53, 54, 56
changes in Python 3.0, 600, 605
% (remainder) operator, 580
& (bitwise and) operator, 580
* (multiplication) operator, 580
* (parameter splicing) operator, 126, 127, 129
Python 3.0, 602, 603, 604, 606
** (exponential) operator, 580
** (keyword splicing) operator, 128, 129, 604
+ (unary plus) operator, 580
+= operator, 522
- (unary minus) operator, 580
/ (division) operator, 580
== (equality) operator, 15, 93, 569, 580
^ (bitwise exclusive or) operator, 580
__(double underscores), 151
| (bitwise or) operator, 580
~ (bitwise negation) operator, 580
<, <= (less than) operators, 580
<< (left shift) operator, 580
>, >= (greater than) operators, 580
>> (right shift) operator, 580
2to3 (automatic refactoring tool), 599
ABBREV.txt file, 300, 301, 302
ABCMeta metaclass, 601
abspath function, 494
abstract classes, Python 3.0, 601, 605
see also OOP (object-oriented programming)
changes in Python 3.0, 601
documenting functions, 116
Fibonacci numbers program, 113–114
inheritance, 147
making code reusable, 212
program structure, 114
value of abstraction, 121
accept method, socket class, 306
access attribute
publisher handler, mod_python, 342, 343
accessor methods, 187
as attributes of property function, 188
private attributes, 151
Acrobat Reader, getting, 425
action method, rule objects
instant markup project, 412, 414
actual parameters see arguments
add function, operator module, 144
add method
chat server project, 479
set type, 229
wx.BoxSizer class, 285
addDestination method, NewsAgent class, 459
addFilter method, Parser class, 414, 415
adding, sequences, 37
addition operator (+), 37
address family, stream socket, 306
addRule method, Parser class, 414, 415
addSource method, NewsAgent class, 459
Adobe Acrobat Reader, getting, 425
Albatross, 344
alignment, string formatting, 56, 58
all function, 581
all variable, 219
allow_reuse_address attribute
SimpleXMLRPCServer class, 527
altsep variable, os module, 224
and operator
Boolean operators, 96
short-circuit logic, 574
operator precedence, 579
Anjuta environment, 6
announcements
comp.lang.python.announce group, 597
any function, 581
Apache web server
configuring to use, 338
conflicting configuration definitions, 339
dynamic web pages with CGI, 328
apilevel property, Python DB API, 294
APIs
App class, wx module see wx.App class
append method, lists, 43, 522, 585
append mode, open function (files), 262
appending to dictionaries, 71, 79
appendleft method, deque type, 232
application frameworks
web application frameworks, 343
changes in Python 3.0, 604, 606
Arachno Python environment, 6
banana about to be squished, 566
Banana class, 558
banana.png file, 556
config.py file, 556
further exploration, 567
Game class, 565
game states, 556
GameOver class, 564
goals, 548
Info class, 563
Level class, 560
LevelCleared class, 564
Paused class, 561
preparations, 551
pygame module, 548
pygame.display module, 549
pygame.event module, 550
pygame.font module, 550
pygame.image module, 551
pygame.locals module, 549
pygame.mouse module, 550
pygame.sprite module, 550
Squish opening screen, 566
SquishSprite class, 557
StartUp class, 564
State class, 559
Weight class, 558
weight.pny file, 554
archive files
args parameter/object, 377, 378
argument splicing, Python 3.0, 604
arguments
calling functions without, 572
command-line arguments, 223
levels of configuration, 398
default arguments, 572
function parameters and, 118
methods, 573
named arguments, 572
printing arguments, using in reverse order, 223
argv variable, sys module, 222, 223
levels of configuration, 398
arithmetic operators, 9
precedence, 580
arithmetic sequence, 184
arraysize attribute, cursors, 297
as clause
changes in Python 3.0, 605
import statement, 85
ascii constants, string module, 60
ASCII encoding error
handling special characters, 451
asctime function, time module, 233
assert method, TestCase class, 356
assert statements, 97, 118, 589
assertAlmostEqual method, TestCase class, 356
assertEqual method, TestCase class, 356
using instead of failUnless, 360
AssertionError class, 589
assertNotAlmostEqual method, TestCase class, 356
assertNotEqual method, TestCase class, 356
assertRaises method, TestCase class, 356
assignment (=) operator, 569
augmented assignments, 87, 589
chained assignments, 87
changing lists, 41
slice assignments, lists, 42
asterisk width specifier, 59
async_chat class
chat server project, 473
collect_incoming_data method, 473, 475
found_terminator method, 473, 475
handle_close method, 475
push method, 475
set_terminator method, 473, 475
asynchat module, 310
async_chat class, 473
asynchronous I/O
multiple connections, 312
asyncore module, 310
chat server project, 470
dispatcher class, 471
loop method, 472
tools for chat server project, 470
Atom, 345
Atox, 424
see individual method names
attribute reference precedence, 580
AttributeError class, 162
checking if object has specific attribute, 172
__getattr__ method, 192
accessing attributes of objects, 150–152
accessor methods defining, 187–188
binding to functions, 150
checking if object has specific attribute, 172
double underscores in attribute name, 116
encapsulation, 146
magic attributes, 116
object-oriented design, 157
private attributes, 151
screen scraping using HTMLParser, 326
special attributes, 116
attrs argument, handle_starttag, 326
atx, 424
augmented assignments, 87, 589
auth/auth_realm attributes
publisher handler, mod_python, 342, 343
automated tests, 351
automatic checkers
limits to capabilities of, 361
PyChecker/PyLint tools, 359–362, 364
automatic refactoring tool (2to3), 599
AWT (Abstract Window Toolkit), 290
backquotes, Python 3.0, 604, 605
backslash character ()
escaping quotes, 23
escaping, regular expressions, 243
backticks
representing strings, 25
backtracking, generators
solving Eight Queens problem, 200–201
backup parameter, input function, 226
BaseRequestHandler class
SocketServer module, 311
bases attribute, 155
issubclass method, 154
basestring class, Python 3.0, 605
basestring function, 581
BasicTextParser class, 422
“batteries included” phrase, 221
BBCode, 424
bdist command, Distutils, 387
formats switch, 387
rpm format, 387
Beautiful Soup module, 327–328
Berkeley DB, 515
Binary constructor, Python DB API, 298
binary literals, Python 3.0, 606
binary mode, open function (files), 262
binary search
recursive function for, 136–138
BINARY value, Python DB API, 298
bind method, socket class, 306
Bind method, widgets, 286, 291
binding parameters, 572
bitwise operators, 580
BlackAdder environment, 6
blit function, 549
blitting, 549
blocking, 306
blockquote element, bulletin board project, 504
finding blocks of text, 406–407
blocks generator
instant markup project, 406
blogs, 597
Boa Constructor environment, 6
body method, NNTP class, 455, 457
bool function, 581
Boole, George, 89
short-circuit logic, 96
Boost.Python, 371
bottlenecks
bound methods, 150
calling unbound superclass constructor, 180
BoxSizer class, wx module see wx.BoxSizer class
else clause, try/except statement, 168
extracting subject of an article, 457
infinite recursion, 134
using with for and while loops, 105
while True/break idiom, 104–105, 271
broadcast method, Node class
chat server project, 479
XML-RPC file sharing project, 521, 522, 525, 532
browsers
open function, webbrowser module, 225
buffering argument, open function (files), 263
buffers
closing files after writing, 267
updating files after writing, 268
bugs see debugging
build command, Distutils, 384, 385
build subdirectory, Distutils, 385
build_ext command, Distutils, 389
built-in functions, 16, 581–584
built-in string formatting, Python 3.0, 605
bulletin board project, 499–515
creating database, 501
database password, 503
further exploration, 515
hidden inputs, 510
main page, 513
message composer, 514
message viewer, 514
requirements, 500
simple.main.cgi script, 505
testing, 513
tools, 500
Button class, wx module see wx.Button class
buttons
adding button to frame, 281
Bind method, widgets, 286
event handling, 286
setting button label, 282
setting button size/position, 283
wx.EVT_BUTTON symbolic constant, 286
bytearray class, Python 3.0, 600
bytes class, Python 3.0, 600
bytes literals, Python 3.0, 605
bytes type, Python 3.0, 599, 605
BytesIO, Python 3.0, 605
c (%c) conversion specifier, 57
C extensions, 371
C programming
deallocating objects, 376
extending Python for improved speed, 365–366
importing existing (shared) C libraries, 370
including C/C++ directly in Python code, 370
Python/C API, 375
reference manual, 596
C# class
IronPython extending Python, 368
C++
enabling interoperability Python/C++, 371
including C/C++ directly in Python code, 370
caching
XML-RPC file sharing project, 534
callable function, 115, 157, 159, 581
callback method, Handler class, 411
callback methods, HTMLParser, 325
callproc method, cursors, 297
Canvas class, pdfgen module, 427
capitalize method, strings, 586
capwords function, string module, 63, 66
cat command, files, 265
catching all exceptions, 167, 169
catching exception object, 166
catching many exceptions in one block, 166
description, 173
raising exceptions again, 164–165
using more than one except clause, 165–166
cElementTree, 437
center method, strings, 586
CGI (Common Gateway Interface)
bulletin board project, 502, 506
simple_main.cgi script, 505
CGI handler, mod_python, 336, 338–339
CGI script, 331
description, 347
dynamic web pages with, 328–336
adding the pound bang (#!) line, 329
setting file permissions, 329–330
getting information from CGI script, 335
input to CGI script, 333
invoking CGI scripts without forms, 334
performance using CGI handler, 339
remote editing with CGI project, 489–498
running CGI script, 339
security risks, 330
using cgi module, 333
cgi file name extension, 329, 339
cgi module
description, 310
dynamic web pages with CGI, 328, 333
FieldStorage class, 333
remote editing with CGI project, 489, 490
cgi-bin subdirectory, 329
cgitb module
remote editing with CGI project, 490
tracebacks, 502
chained assignments, 87
chained comparison operators, 93
character sets, 243
characters event handler
advantages of writing, 469
asynchat module, 473
asyncore module, 471
collecting data (text) coming from client, 473
command interpretation, 477–478
further enhancement, 486
listening on port for incoming connections, 471
requirements, 469
tools, 470
chat services, 469
ChatServer class, 480, 484, 471–473
ChatSession class, 480, 484, 473–475
enter method, 480
checkIndex function, 185
CherryPy, 344
chmod command, UNIX, 330
choice function, random module, 144, 159, 235
chunks attribute
screen scraping using HTMLParser, 326
clamp method, rectangles, 556
class attribute
finding out class of an object, 155
class decorators, Python 3.0, 601, 605
class definition statement, 594
class keyword, 573
cls parameter, 190
self parameter, 189
class scope variable, 153
class statement, 149
self parameter, 149
superclasses, 153
abstract classes, 601
accessing attributes of objects, 150–152
accessor methods, 151
built-in exception classes, 162
changes in Python 3.0, 605
class decorators, 601
class statement, 149
classes and types, 147
new-style classes, 206
custom exception classes, 163
defining, 573
distinguishing methods from functions, 150
inheritance, 141, 147–155, 159
instances, 147
isinstance method, 155
metaclasses, 176
method definitions, 149
naming conventions, 148
new-style/old-style classes, 149, 175, 206
implementing properties with old-style classes, 191
Python version, 3.0, 176
object-oriented design, 157, 158
overriding methods, 206
property function, 189
specifying superclasses, 153–154
subclassing built-in classes, 175
superclasses, 147
multiple superclasses, 155–156
classmethod function, 581
clear method, dictionaries, 74–75, 585
clear method, Group class
Clearsilver, 341
Client class
fetchHandler, 538, 540, 541, 544
OnInit method, 538, 539, 541, 543
XML-RPC file sharing project, 528, 533
clients
XML-RPC file sharing project, 527–528
close function, fileinput module, 226
finding sender of e-mail, 253
close method, connections, 296, 300
bulletin board project, 503
close method, cursors, 297
close method, generators, 199
closeHandler, Java Swing, 290
clpa_server variable, 458
cls parameter, class methods, 190
cmath module, 18
Cmd class, cmd module, 527
modeling command interpretation on, 477
cmd module, 259
XML-RPC file sharing project, 519
cmp argument, sort method, 605
making comparisons, 93
code
making code reusable, 212
reading source code to explore modules, 221
source code checking, 359
code coverage, testing, 351
Code Crusader environment, 6
code fatigue, 395
Code Forge environment, 6
code reuse, 212
coerce function, Python 3.0, 604, 606
collect_incoming_data method
collections
see also mappings; sequences
collections module, 231
combine function, 132
command interpretation
modeling on Cmd class, 477
command prompt
running scripts from, 20
CommandHandler class
command-line arguments, 223
levels of configuration, 398
command-line switches, 398
command-line tools
using with subprocess module, 360
commands
cat command, 265
import command, 17
pipe characters linking, 265
python command, 265
sort command, 265
commas
separating print statements with, 83–84
documenting functions, 116
commit method, connections, 296, 300
bulletin board project, 503
save.cgi script, 511
Common Gateway Interface see CGI
comp.lang.python group, 597
chaining, 93
comparing incompatible types, 92
comparing sequences, 95
comparing strings, 94
equality operator, 93
in operator, 94
membership operator, 94
compile function, re module, 245
compiling extensions, Distutils, 388–389, 390
complex function, 581
complex numbers, 18
Complex type, 579
components see widgets
comprehensions, 603
computer games
concatenating strings, 24
condition method, rule objects, 412, 413, 414
conditional operator, 96
assertions, 97
conditional execution, 90
description, 111
elif clauses, 91
else clauses, 90
if statements, 90
nesting blocks, 91
short-circuit logic, Boolean operators, 574
config.py file, 397
arcade game project, 556
renamed modules in Python 3.0, 604
levels of, 398
dividing into sections, 397
conflict function, Eight Queens problem, 202
connect function, Python DB API, 300, 304
parameters, 296
connect method, socket class, 306
bulletin board project, 503, 511
connectionLost event handler, 317
connectionMade event handler, 317
connections
bulletin board project, 502
console I/O, Python 3.0, 600
constants, 396
string module, 60
symbolic constants, 396
creating, 177
default parameters, 574
description, 206
using super function, 180, 181
Python DB API, 297
unbound superclass constructor, 179–180
containers, 32
content handlers
dispatcher mix-in classes, 446
ContentHandler class
XML parsing project, 451
xml.sax.handler module, 439
Content-type header
dynamic web pages with CGI, 331
context managers, 268
continual rewriting syndrome, 395
using with for and while loops, 105
control structures, 569
conversion flags, 56
conversion specifiers, 56
% character, 56
dictionaries, 73
minimum field width, 57
tuples, 56
conversion types, string formatting, 56, 57
conversions
between numbers and strings, SQLite, 303
convert function, 301
convert method, surface objects, 554
Cookie module, 310
cookie-cutter code
automating, 377
cookielib module, 310
copy function, copy module, 220
copy method, dictionaries, 75, 585
count method, strings, 586
coverage
code coverage, 351
CPython, extending, 367, 369–371
cracking, vs. hacking, 1
CREATE TABLE command
bulletin board project, 501
create_socket method
cStringIO, Python 3.0, 605
csv module, 258
ctypes library, 370
cursor method, connections, 296, 300
cursor objects, 296
in bulletin board project, 503—505
cursors, Python DB API, 296–297, 303
attributes, 297
bulletin board project, 503
methods, 296
custom exception classes, 163, 173
CXX see PyCXX
cyclic garbage, 377
%d conversion specifier, 56
Daily Python-URL blog, 597
Dalke, Andrew
Sorting Mini-HOWTO, 49
data
analyzing many forms of numeric data, 370
fetching data from Internet, 432
containers, 32
mappings and dictionary type, 69
stacks, 45
Database API see Python Database API
database parameter
connect function, Python DB API, 296
DatabaseError exception, Python DB API, 295
databases
compact table-based databases, 293
food database application, 300–303
importing data into, 301
key-value databases, 293
object databases, 293
popular commercial choices, 293
relational databases, 293
supported by Python packages, 293
DataError exception, Python DB API, 295
datagram socket, 306
dataReceived event handler, 317
Date constructor, Python DB API, 298
DateFromTicks constructor, Python DB API, 298
dates
fields of Python date tuples, 233
datetime module, 234, 258, 456
DATETIME value, Python DB API, 298
DB API see Python Database API
deallocating objects, 376
Debian Linux, installing Python, 4
debugging
anticipating code changes, 351
PythonDebug directive, 339, 340
remote editing with CGI project, 490
decode method, strings, 586
decorators
abstract classes, Python 3.0, 601
changes in Python 3.0, 605
class decorators, Python 3.0, 601
description, 190
deep copy, dictionaries, 76
deepcopy function, copy module, 76, 220
class namespace, 152
documenting functions, 116
generator-function component, 198
default arguments, 572
default values, parameters, 124
using empty lists as, 575
defaultdict dictionary, 232
defaultStart/defaultEnd methods
deferred execution, Twisted, 317
definitions
class definitions, 594
function definitions, 594
del method, 177
del operation, dictionaries, 71
deleting elements from lists, 41
description, 112
using for cleanup operation, 170
delattr function, 581
__delattr__ method, 191
deque module, 259
collections module, 231
description attribute, cursors, 297
descriptor protocol, 189
design
object-oriented design, 157–158
destructors
__del__ method, 177
__dict__ attribute
avoiding endless looping, 192
__getattribute__ method trap, 192
seeing all values stored in objects, 157
dictfetchall method, cursor object
bulletin board project, 503, 504
SQLite alternative, 505
dictfetchone method, cursor object
bulletin board project, 503
dictionaries, 571
accessing dictionary items, 76
assigning value to new key, 71
checking if key exists, 78
constructing from other mappings, 71
conversion specifiers, 73
creating, 70
creating with values of None, 76
deep copy of, 76
defaultdict, 232
empty dictionary, 604
globals function, 132
iterating over, 100
keys, 121
keys and values, 70
locals function, 132
modules mapping, 222
overwriting same key items from another, 80
precedence, 581
removing all items from, 74
removing arbitrary value from, 79
returning all items of, 78
returning list of keys, 78
returning list of values, 80
returning value of specified key, 79
shallow copy of, 75
string formatting with, 73, 81
subclassing dict type, 185–187
uses, 69
dictionary comprehension, Python 3.0, 603
dictionary methods, 74–80, 585–586
dictionary type
deepcopy function, 76
in operation, 71
key related operators, 71
mappings and, 69
syntax, 70
types for keys, 72
uniqueness of values, 70
using, 70
dictionary views, Python 3.0, 603
difflib library, 258
digests, passwords, 494
digits constant, string module, 60
exploring modules, 218
directory element
XML parsing project, 437
directory list
XML parsing project, 448
discussion forum
bulletin board project, 499–515
dispatch method
XML parsing project, 445
Dispatcher class
chat server project, 471
create_socket method, 471
garbage collection, 480
handle_accept method, 471, 472, 475, 480
set_reuse_addr method, 473
display method, Level class, 561
display method, State class, 560
display module, pygame, 549
dist subdirectory, Distutils, 387
distribute method, NewsAgent class, 459, 462
distributing operators, 128–129, 604
distribution formats, 387
distributions
ActivePython, 595
alternative Python distributions, 5–7
distributing Python packages, 383
IronPython, 595
Jython, 595
MacPython, 595
Official Python Distribution, 595
Python distributions, 595
bdist command, 387
build subdirectory, 385
build_ext command, 389
dist subdirectory, 387
install command, 385
installing, 384
lib subdirectory, 385
py_modules directive, 386
register command, 390
setup.py script, 383, 384, 385, 387, 390
setuptools project, 384
wrapping modules as archive file, 386–387
division (/) operator, 580
double slash (//) operator, 10
integer division, Python 3.0, 604, 605
rounding, 16
divmod function, 581
do_exit method, Client class
XML-RPC file sharing project, 533
do_fetch method, Client class
GUI client project, 538
XML-RPC file sharing project, 533
do_logout method, chat server project, 479
do_look method, chat server project, 480
do_say method
chat server project, 480
XML-RPC file sharing project, 527
do_who method, chat server project, 480
doc attribute
exploring modules, 220
function attributes, 116
doc parameter, property function, 189
exploring modules, 220
doctest module, 352, 353–355, 364
testmod function, 353, 354, 364
Document Object Model (DOM), 439
documentation
creating graphics and documents in PDF, 425
Macintosh library modules, 596
Python, 596
DOM (Document Object Model), 439
DOS, handling whitespace for, 225
double slash operator, 10
double underscores (__)
making method or attribute private, 151
double-clicking, 21
double-ended queues (deques), 231–232
drawToFile method, renderPDF class, 428
dsn parameter
connect function, Python DB API, 296
duck typing, 145
dynamic web pages
screen scraping, 321
dynamic web pages with CGI, 328–336
%E, %e conversion specifiers, 57
Eclipse environment, 6
edit.cgi script
bulletin board project, 510, 511
description, 507
link from main.cgi, 507
link from view.cgi, 508
testing, 513
remote editing with CGI project, 492–494, 496
editing
remote editing with CGI project, 489–498
eggs, Python, 384
ElementTree, 437
dealing with XML in Python, 439
elif clauses, if statements, 91, 592
else clauses
combining try/except/finally/else, 170
description, 173
using in loops, 105
email, finding sender of, 251–253
email addresses filter
instant markup project, 418
email module, 310
EmailDestination class
news gathering project, 468
empty dictionary, 604
empty lists, 37
using as default value, 575
empty set, 604
enable function, cgitb module, 331, 347
accessing attributes of objects, 150–152
accessor methods, 187
attributes, 146
extending Python, 366
state, 147
encode method, strings, 586
encoding, Python 3.0, 599, 605
end method
MatchObjects, re module, 248
end method, Handler class
instant markup project, 410, 411
endElement event handler
XML parsing project, 440, 441, 445
endless loop trap
setattr method, 192
EndSession exception
chat server project, 479
endswith method, strings, 586
ensureDirectory method
enter method
context managers, 268
enter method, ChatSession class, 480
enumerate function, 102, 112, 582
environ mapping, os module, 223, 224
environment variables
description, 216
environ mapping, os module, 224
levels of configuration, 398
PYTHONPATH, 215
setting in UNIX and Mac OS X, 216
setting in Windows, 216
EOF command, 527
Epytext
markup systems and web sites, 424
equality (==) operator, 15, 93, 569, 580
eric environment, 6
Error exception, Python DB API, 295
error handling
exceptions, Python DB API, 295
error messages see tracebacks
errors
see also exceptions
AttributeError class, 162
catching Pygame-specific errors, 549
distinguishing from failures in unittest, 357
inappropriate type used, 183
index outside range, 183
IndexError class, 162
IOError class, 162
KeyError class, 162
NameError class, 162
NotImplementedError exception, 224
stderr stream, sys module, 222
TypeError class, 163
ValueError class, 163
ZeroDivisionError class, 161, 163
escape function, re module, 245, 247
escaping special characters
regular expressions, 242
EtText, 424
sample template system, 254
eval statements, 110
description, 112
scope, 111
event handling
Bind method, widgets, 286
button events, 286
chat server project, 471
closeHandler, Java Swing, 290
connectionLost event handler, 317
connectionMade event handler, 317
dataReceived event handler, 317
description, 291
HTMLParser callback methods, 325
load function, 286
rawDataReceived event handler, 318
save function, 286
screen scraping using HTMLParser, 326
when event handler is called, 286
writing Twisted server, 317
wx.EVT_BUTTON symbolic constant, 286
wxPython GUI toolkit, 286
XML parsing project, 439–441, 448–450
event module, pygame, 550
event-driven networking framework, 316
writing Twisted server, 317
events, 286
polling event constants in select module, 315
except block
Python 3.0, 605
Python DB API, 295
except clause, try statement, 593
see also try/except statements
catching all exceptions, 167
catching exception object, 166
catching many exceptions in one block, 166
description, 173
trapping KeyError exception, 172
using more than one except clause, 165–166
Exception class, 162
catching all exceptions, 169
raise statement, 162
catching, 166
see also errors
built-in exception classes, 162, 163
catching all exceptions, 167, 169
catching exception object, 166
catching many exceptions in one block, 166
danger of catching all exceptions, 167
description, 173
raising exceptions again, 164–165
connecting to NNTP servers, 455
custom exception classes, 163, 173
doing something after exceptions, 169–170
EndSession exception, 479
exception hierarchy, 295
functions and, 164, 170–171, 173
GeneratorExit exception, 199
indicating everything worked, 168–169
NotImplementedError exception, 224
Python DB API, 295
raising exceptions, 161–163, 173
StopIteration exception, 192
SyntaxError exception, 254
using more than one except clause, 165–166
warnings, 173
XML-RPC file sharing project, 528–529
changes in Python 3.0, 606
description, 112
replacing reload function functionality using, 211
sample template system, 254
scope, 111
execfile function, 582
executable binaries, 390
executable Windows programs
execute method, cursors, 297, 301, 302
bulletin board project, 503
executemany method, cursors, 297, 301
execv function, 224
exit command
XML-RPC file sharing project, 527
exit function, sys module, 222
exit method
context managers, 268
expandtabs method, strings, 586
exponentiation operator (**), 11
compared to pow function, 16
precedence, 580
expression statements, 589
compared to statements, 13
description, 29
evaluating expression strings, 254
logical expressions, 573
precedence, 580
extend method
deque type, 232
architecture, 366
CPython, 367
encapsulation, 366
extension approaches, 380
identifying bottlenecks, 365
Python extensions, 380
using Python/C API, 380, 375–380
framework for extensions, 377–378
hand-coded palindrome module, 379–380
wrapping legacy code, 366
extendleft method
deque type, 232
extensions
compiling extensions, 388–389, 390
py2exe extension, Distutils, 389–390
%F conversion specifier, 57
%f conversion specifier, 54, 57
factorial function, 135
factorials
recursive function to calculate, 134
Factory class
twisted.internet.protocol module, 317
fail method, TestCase class, 357
failIf method, TestCase class, 357
failIfAlmostEqual method, TestCase class, 356
failIfEqual method, TestCase class, 356
failUnless method, TestCase class, 356
using assertEqual instead of, 360
failUnlessAlmostEqual method, TestCase class, 356
failUnlessEqual method, TestCase class, 356
failUnlessRaises method, TestCase class, 357
failures
distinguishing from errors in unittest, 357
False value (Boolean), 89
changes in Python 3.0, 605
Fault class, xmlrpclib module, 528, 529
feed method
instant markup project, 410
feeds see RSS feeds
fetch command
XML-RPC file sharing project, 527
fetch method, Node class
XML-RPC file sharing project, 520, 521, 524, 526, 527, 531
fetchall method, cursors, 297, 302
bulletin board project, 503, 504
fetchHandler, Client class
GUI client project, 538, 540, 541, 544
fetchmany method, cursors, 297
fetchone method, cursors, 297
bulletin board project, 503
fget/fset/fdel parameters, property function, 189
Fibonacci numbers program, 113
field width, string formatting, 56, 57, 59
FieldStorage class, cgi module, 333
file locking
remote editing with CGI project, 497
flush method, 268
read method, 264
readline method, 266
readlines method, 266
seek method, 266
tell method, 266
write method, 264
writelines method, 267
xreadlines method, 272
file permissions
dynamic web pages with CGI, 329–330
file property, modules
exploring modules via source code, 221
file sharing, 517
adding GUI client to Python program, 537–545
XML-RPC file sharing project, 517–535
filecmp module
news gathering project, 468
description, 259
finding sender of e-mail, 252
functions, 225
lazy line iteration with fileinput, 272
sample template system, 255, 256
filelineno function, fileinput module, 226
filename function, fileinput module, 226
files
file types, 274
finding file name, wxPython, 286
iterating over file contents, 270–274
description, 274
iterating over lines in very large file, 272
lazy line iteration with fileinput, 272
one line at a time, 271
reading everything first, 271
without storing file object in variable, 273
buffering, 263
changes to file in text mode, 262
description, 274
random access, 266
read/write/append/binary modes, 261
reading and writing, 264
closing files after, 267
reading files, 274
streams, 274
universal newline support mode, 263
using as context managers, 268
validating file names, XML-RPC, 529–534
writing files, 274
updating files after writing, 268
Filter class, 154
filter function, 138, 139, 140, 582
changes in Python 3.0, 605
instant markup project, 414
filters
fetching data from Internet, 432
instant markup project, 409, 413, 418
filterwarnings function, 174
finally clause, try statement, 169–170, 173, 593
combining try/except/finally/else, 170
findall function, re module, 245, 246
finding sender of e-mail, 252
findall method, regular expressions
news gathering project, 462
firewalls, network programming and, 305
firstDisplay method
flag argument, wx.BoxSizer class, 285
flags
conversion specifiers, 56
flags parameter, 247
flip function, arcade game project, 549, 552
food database application, 300
Float type, 579
floating-point numbers, 10
floats, 10
flush method, files, 268
Font function, arcade game project, 550
font module, pygame, 550
food database application, 300–303
creating and populating tables, 301–302
food_query.py, 303
importdata.py, 301
searching and dealing with results, 302–303
footers
writeFooter method, 446
Fibonacci numbers program, 113
generators
iter method, 193
iterable files, 272
recursive generators, 196
for statements, 593
forking, 312
chat server project, options for, 469
multiple connections, 312
SocketServer module, 313
form tag, action attribute, 492
formal parameters, 118
format function, bulletin board project, 504, 507
format method, strings
changes in Python 3.0, 600
format strings, Python/C API, 378
formats switch
bdist/sdist commands, Distutils, 387
formatting strings
changes in Python 3.0, 600
string formatting operator, 53
forms
invoking CGI scripts without, 334
forums, online Python resources, 597
found_terminator method
chat server project, 473, 475, 479
Frame class, wx module see wx.Frame class frames
adding button to frame, 281
setting frame size, 283
setting frame title, 282
wx.Frame class, 281
wxPython GUI toolkit creating, 281
frameworks
event-driven networking framework, 316
framework for extensions, 377–378
SocketServer framework, 310–311, 319
Twisted framework, 316–319, 320
web application frameworks, 343
freshmeat.net, 596
from module import statement, 17
reasons not to use, 18
fromkeys method, dictionaries, 76, 585
frozenset function, 582
frozenset type
immutability, 229
ftplib module, 310
function annotation, Python 3.0, 601
function attributes
doc attribute, 116
function call precedence, 580
function definition statement, 115, 594
functional programming, 138–139, 140
functional requirements
requirement specification, 350
see individual function names
as values in Python, 572
binding attributes to, 150
built-in functions, 16, 581–584
calling functions without arguments, 572
containing yield statement, 195
defining functions in modules, 212
distinguishing methods from, 150
documenting, 116
ending functions, 117
exceptions and, 164, 170–171, 173
extinct functions in Python 3.0, 604
flags parameter, 247
formal parameters, 118
from module import statement, 17
function definition, 139
functions without return values, 117
local naming, 120
methods compared, 43
nested scopes, 133
number of scopes/namespaces, 131
object-oriented design, 157
parameter/return type annotation, 601, 605
collecting parameters, 125–128
distributing operators, 128–129, 604
gathering operators, 125–128, 602, 603, 604, 606
immutability, 123
keyword-only parameters, 602, 606
passing parameters to functions, 572
values, 118
parts of recursive function, 134
recursive functions, 134
return value, 16
caution using if statements, 117
return value is None, 117
type objects, 17
functools module, 258
%G, %g conversion specifiers, 57
games, arcade game project, 547–567
Game class, 565
game states, 556
GameOver class, 564
garbage collection
cyclic garbage, 377
del method, 177
gc module, 377
reference counting, 377
unbound objects, 480
gathering operators, 125–128, 602, 603, 604, 606
gc module, 377
generator comprehension, 196
GeneratorExit exception
close method, generators, 199
close method, 199
components of, 198
description, 207
generator-iterator, 198
making generators, 195
send method, 198
simulating, 199
solving Eight Queens problem, 200–206
throw method, 199
Gentoo Linux
installing Python, 4
get function, arcade game project, 550, 552
GET method
getting information from CGI script, 335
get method, dictionaries, 76–78, 585
get_surface function, arcade game project, 549, 552
raising AttributeError, 192
getattr function, 157, 159, 582
chat server project, 478
checking whether object has specific attribute, 173
working with getattr method, 192
__getattribute__ method, 191
accessing dict attribute, 192
getdefaultencoding function, sys module, 451
gethostname function, socket class, 306, 307
getitem method, 182
changes in Python 3.0, 606
overriding, 186
simulating slicing, sequences, 185
subclassing list type, 186
getItems method, NewsAgent class
news gathering project, 459, 461, 462
getName accessor method
private attributes, 151
getopt module, 259
news gathering project, 468
getPort function
XML-RPC file sharing project, 523, 530
getrandbits function, random module, 235
getslice method, Python 3.0, 606
GetValue method
load event, wxPython, 286
save event, wxPython, 286
getvalue method, FieldStorage class
input to CGI script, 333
global scope, 131
exceptions and functions, 170
rebinding variables in outer scopes, 133
global statements, 592
global variables
avoiding, 240
bugs when referencing, 132
constants, 396
object-oriented design, 157
rebinding, 132
shadowing, 132
treating objects as abstract, 146
gmtime function, time module, 234
Gnutella, 517
gopherlib module, 310
Graphical User Interfaces see GUIs
graphics
creating graphics in PDF/Python, 425
graphics creation project, 425–434
constructing PolyLine objects, 429–430
drawing with ReportLab, 427–429
fetching data from Internet, 432
further exploration, 434
preparations, 426
prototype for sunspots_proto.py, 430–431
ReportLab package, 425
tools, 426
graphics package, reportlab module, 427
graphics-generating package
graphics creation project, 426
graphs
definitions and further information, 201
greater than operators, 580
greedy patterns, 250
finding sender of e-mail, 252
grokking, 218
Group class, arcade game project, 550
clear method, 552
update method, 552
group method
connecting to NNTP servers, 455
MatchObjects, re module, 248
group numbers, regular expressions
using in substitution string, 249
groups
Usenet groups, 597
Grutatxt, 424
GTK platform
PyGTK GUI toolkit, 278
further exploration, 545
ListableNode class, 541
preparations, 538
requirements, 537
tools, 537
GUI toolkits
chat server project, 486
choosing between, 278
description, 277
for Jython, 290
list of GUI toolkits for Python, 597
popular GUI Toolkits for Python, 277
Swing, 290
Tk/Tkinter, 289
wxPython, building text editor, 278–288
GUIs (Graphical User Interfaces), 291
hacking
cracking compared, 1
halting theorem, 361
halts module, 362
handle method
forking and threading, 313
handle method, Node class
XML-RPC file sharing project, 521, 522, 525, 531
handle_accept method
chat server project, 471, 472, 475, 480
handle_charref method, HTMLParser, 325
handle_close method
handle_comment method, HTMLParser, 325
handle_data method, HTMLParser, 325, 326
handle_decl method, HTMLParser, 325
handle_endtag method, HTMLParser, 325, 327
handle_entityref method, HTMLParser, 325
handle_pi method, HTMLParser, 325
handle_startendtag method, HTMLParser, 325
handle_starttag method, HTMLParser, 325, 326
Handler class, instant markup project, 410–411, 418
callback/start/end/sub methods, 410, 411
handler module, xml.sax, 439
handlers
CGI handler, mod_python, 336, 338–339
creating content handler, 439–441
instant markup project, 409–411
mod_python handler framework, 336
PSP handler, mod_python, 336, 339–341
publisher handler, mod_python, 336, 341–343
handlers.py, instant markup project, 418
has_key method, dictionaries, 78, 585, 606
hasattr function, 157, 159, 582
replacing callable function, 115
working with getattr method, 192
hashlib module, 258
head method, NNTP class, 455, 457
header file
framework for extensions, 377
headers
writeHeader method, 446
heading rules
instant markup project, 415
HeadingRule class
instant markup project, 416, 420
HeadlineHandler class
XML parsing project, 441
heappush function, 230
heapreplace function, 230, 231
hello method, Node class
XML-RPC file sharing project, 520, 521, 524, 526, 528, 531, 534
help switch, Distutils, 384
hex function, 582
hexadecimal numbers, 12
hidden form elements
remote editing with CGI project, 494
hidden inputs, 510
bulletin board project, 513
host parameter, connect function, 296
hotshot module, 363
HTML
automatically marking up plain-text file, 403
fixing ill-formed HTML, 322
index.html file, 492
introduction to, 403
parsing, 322
XHTML advantages over, 325
HTMLDestination class
news gathering project, 460, 462
htmllib module
parsing HTML, 322
callback methods, 325
event-handling methods, 325
screen scraping using, 326
HTMLRenderer class
instant markup project, 409, 411, 419
httplib module, 310
%i conversion specifier, 56
id column, messages table
bulletin board project, 502
view.cgi script, 508
id function, 582
IDEs for Python, 6
IDLE interactive Python shell, 2
IDEs for Python, 6
saving and executing programs, 19
if statements, 15, 90, 569, 592
catching exceptions, 164
caution when return value is None, 117
try/except statement compared, 171, 173
image attribute, Sprite class, 554
image module, pygame, 551
imaginary numbers, 18
imaplib module, 310
immutability
frozenset type, 229
lists, 119
parameters, 123
set type, 229
strings/numbers/tuples, 119
using is operator with immutable values, 94
implementation of projects
structure of projects in this book, 402
import command, 17
from module import statement, 17
import statements, 591
as clause, 85
description, 111
fetching functions from external modules, 209
importing something as something else, 84–85
open function, 85
importdata.py, 301
importing modules, 259
import-only-once behavior, modules, 211
in operation, 71
operator precedence, 580
include_dirs variable, 299
incompatibility warnings
transitioning to Python 3.0, 599
indentation, 569
blocks, 88
index method, lists, 44, 138, 585
index method, strings, 587
index, sequences
checkIndex function, 185
description, 31
illegal type of index used, 184
index.html file
remote editing with CGI project, 492, 496
IndexError class, 162
indexing, lists, 570
inequality operator
infinite recursion, 134
inflate method, rectangles, 555, 556
Info class, arcade game project, 563
information-gathering agent
news gathering project, 453
multiple inheritance, 156, 575
multiple superclasses, 155–156
object-oriented design, 157
overriding methods and constructors, 177, 178
specifying superclasses, 153–154
subclassing list/dict/str types, 185
init file
making Python recognize packages, 217
init function, pygame module, 549, 552
__init__ method, 575
calling unbound superclass constructor, 180
making init magic, 177
using super function, 180
initialization functions
naming conventions, 380
initializing methods see constructors
inner scope see local scope
Inno Setup installer, 388
inplace parameter, input function, 226, 227
input
compared to raw_input, 26
getting input from users, 14–15
hidden inputs, 510
stdin stream, sys module, 222
input function, 14, 30, 570, 582
changes in Python 3.0, 600
input function, fileinput module, 226
backup parameter, 226
inside attribute, ListRule class
instant markup project, 417
inside function
XML-RPC file sharing project, 530
inspect module
publisher handler, mod_python, 342
seeing all values stored in objects, 157
install command, Distutils, 385
compiling extensions, 388
on Macintosh, 5
installers
alternative installers, 388
creating Windows installer, 387
Inno Setup, 388
introduction, 390
McMillan installer, 388
Windows installer technology, 388
writing install scripts with Distutils, 383–386
instances of classes, 147
isinstance method, 155
instant markup project, 403–424
components, 409
finding blocks of text, 406–407
goals, 404
Rule class, 413
tools, 404
int function, 30, 113, 570, 582
integer type, 579
integers
integer division, 9
numbers containing leading zeros, 70
IntegrityError exception, Python DB API, 295
saving programs, 19
interface file, SWIG, 372, 373
InterfaceError exception, 295
InternalError exception, 295
interoperability
enabling, Python/C++, 371
I/O, asynchronous I/O with select and poll, 313–316
IOError class, 162
IRC, 595
IronPython, 595
alternative Python distributions, 6, 7
description, 380
is not operator, 580
operator precedence, 580
isalnum method, strings, 587
isalpha method, strings, 587
isdigit method, strings, 587
isdir function, os.path module
XML parsing project, 447
isfirstline function, fileinput module, 226
isinstance function, 142, 159, 582
using in checkIndex function, 185
isinstance method, 155
islower method, strings, 587
isspace method, strings, 587
isstdin function, fileinput module, 226
issubclass method, 154
istitle method, strings, 587
isupper method, strings, 587
sequence and mapping protocol, 182–185
subclassing list/dict/str types, 185–187
item access precedence, 580
items method, dictionaries, 78, 100, 585
changes in Python 3.0, 605
for loops, 193
iterable unpacking, Python 3.0, 603, 606
iteration
definition, 192
for loops, 99
iterable object, 99
iterating over dictionaries, 100
iterating over file contents, 270–274
iterating over lines in large file, 272
lazy line iteration with fileinput, 272
one line at a time, 271
reading everything first, 271
without storing file object in variable, 273
iterating over sequences, 32
iterating over string-like objects, 197
looping, 99
numbered iteration, 101
reversed iteration, 102
sorted iteration, 102
StopIteration exception, 192
while loops, 98
iterator return values, Python 3.0, 603
changes in Python 3.0, 605
description, 207
generators and, 195
introduction, 175
making sequences from, 194
returning, 197
iteritems method, dictionaries, 78, 585
iterkeys method, dictionaries, 78, 585
itertools module, 258
itervalues method, dictionaries, 80, 585
Java class, Jython extending Python, 367
Java Swing see Swing GUI toolkit
JavaBean properties
Jython extending Python, 368
JavaScript Object Notation (JSON), 346
join function, os.path module
XML parsing project, 447
example using, 223
performance, 255
JSON (JavaScript Object Notation), 346
just-in-time compiler for Python, 370
Jython, 595
alternative Python distributions, 6, 7
description, 380
GUI toolkits for, 290
JavaBean properties, 368
jythonc command, 367
KDevelop environment, 6
key argument of sort method, lists, 48
changes in Python 3.0, 605
key related operations, dictionaries, 71
key types, dictionaries, 71
KeyError exception, 162
trapping with except clause, 172
keys
inappropriate type used, 183
sequence key is negative integer, 183
keys method, dictionaries, 78, 100, 585
changes in Python 3.0, 605
keys, dictionaries, 121
checking if key exists, 78
types for keys, 72
keyword arguments/parameters, 123–125
** (keyword splicing) operator, 126
combining with positional parameters, 124
keyword-only parameters, 602, 606
sort method, lists, 48
using with wx constructors, 282
Komodo environment, 6
label argument, wx.Button constructor, 282
lambda expressions, 139
lambda operator, 579
languages
object-oriented languages, 141
LaTeX
markup system, 404
typesetting system, 434
layout mechanisms, 291
lazy evaluation, Boolean operators, 96
lazy line iteration, 272
left shift operator, 580
len operation, dictionaries, 71
less command, UNIX, 457
less than operators, 580
letters constant, string module, 60
changes in Python 3.0, 606
Level class, arcade game project, 560
LevelCleared class, arcade game project, 564
lib subdirectory, Distutils, 385
libraries
ctypes library, 370
difflib library, 258
importing existing (shared) C libraries, 370
Macintosh library modules, 596
Python library reference, 596
standard library modules, 259
Tidylib, 324
library_dirs variable, 299
line method, Canvas class, 427
line numbers
adding to Python script, 227
line separators see newline character
lineno function, fileinput module, 226
LinePlot Class
graphics creation project, 432–434
LineReceiver class, Twisted framework
chat server project, options for, 469
LineReceiver protocol
twisted.protocols.basic module, 318
lines
constructing PolyLine objects, 429–430
lines generator
instant markup project, 406
linesep variable, os module, 224
Linux
installing Python on Linux/UNIX, 3–5
list comprehension, 105–106, 112
exploring modules, 218
generator comprehension and, 196
using, 139
list constructor
making lists from iterators, 194
list item rules
instant markup project, 415
list method, ListableNode class
list rules
instant markup project, 415
ListableNode class, GUI client project, 541
listen method
socket class, 306
listenTCP function, reactor module, 318, 320
ListItemRule class
instant markup project, 416, 420
ListRule class
instant markup project, 417, 420
adding items compared to dictionaries, 72
appending object to end of, 43
appending values to end of, 44
assigning to slices, 42
assigning values to, 41
changing lists, 41
copying entire list, 47
counting occurrences of elements in, 43
deleting elements from, 41
deleting slices, 42
empty lists, 37
finding first occurrence of a value, 44
immutability, 119
indexing, 570
initialization, 37
inserting elements, 42
inserting object into, 45
making lists from iterators, 194
making lists from other lists, 105
multiple references to same list, 47
precedence, 581
removing an element from, 45
removing first occurrence of value, 46
reversed function, 47
reversing elements in, 46
selecting all elements, 35
selecting elements from start/end, 35
sorted function, 48
sorting into new list, 47
sorting original list, 47
subclassing list type, 185–187
tuples compared, 31
literal values, 579
ljust method, strings, 587
load function
arcade game project, 551
event handler, 286
local scope, 131
parameters, 118
locals module, pygame, 549, 552
localtime function, 233, 234, 455
logical expressions, 573
short-circuit logic, 574
logical operators see Boolean operators
login command, chat server project, 479, 485, 486
LoginRoom class, chat server project, 479, 480, 482
logout command, chat server project, 479, 485, 486
LogoutRoom class, chat server project, 479, 480, 483
logRequests value
XML-RPC file sharing project, 523
long integer type, 579
changes in Python 3.0, 605
look command, chat server project, 480, 485
lookup function, 121
loop method, chat server project, 472
while True/break idiom, 104, 105
description, 112
__dict__ attribute avoiding endless looping, 192
for loops, 99
iterating over dictionaries, 100
numbered iteration, 101
reversed iteration, 102
sorted iteration, 102
using else clauses in, 105
while loops, 98
lower method, strings, 62, 95, 241, 457, 587
lowercase constant, string module, 60
lstrip method, strings, 587
-m switch
making programs available as modules, 212
Mac OS X
setting environment variables, 216
Macintosh
installing Python on, 5
Macintosh library modules, 596
MacPython, 595
magic attributes
__dict attribute__, 192
magic methods, 575
advanced use of, 187
__del__ method, 177
__delattr__ method, 191
__getattribute__ method, 191, 192
__getitem__ method, 182
__init__ method, 177
modules, 576
__next__ method, 192
__nonzero__ method, 182
overriding methods and constructors, 177–179
calling unbound superclass constructor, 179–180
property function, 189
sequence and mapping protocol, 182–185
__setitem__ method, 182
subclassing list/dict/str types, 185–187
mailbox module, 310
mailcap module, 310
mailing lists, 597
main chat room, chat server project, 479
main function
calling from another function, 240
main page, bulletin board project, 513
main value
testing modules, 213
main.cgi script, bulletin board project, 506, 507–508
link to edit.cgi, 507
testing, 513
MainLoop method, wx.App class, 281
makedirs function, os module
XML parsing project, 447
maketrans function, string module, 60, 65, 66
MANIFEST.in file, 387
changes in Python 3.0, 605
mappings
constructing dictionaries from, 71
deleting element associated with key, 182
dictionaries and, 69
modules mapping, 222
returning number of key-value pairs contained in, 182
returning value of key, 182
sequence and mapping protocol, 182–185
storing value for key, 182
Markdown
markup systems and web sites, 424
markup
instant markup project, 403–424
markup systems, 424
markup.py program, instant markup project, 421
Martelli, Alex, 106
Python Cookbook, 96
match function, re module, 245, 246
MatchObjects class, re module, 247–249
methods, 248
Matplotlib/pylab, 434
MAX_HISTORY_LENGTH constant
peer-to-peer file sharing, 522
maxint value, sys
changes in Python 3.0, 605
maxsplit argument
split function, re module, 246
McMillan installer, 388
membership, 51
checking membership with sets, 228
membership operator, 94
memory leaks, 376
message composer, bulletin board project, 514
Message object, email module
news gathering project, 461
message viewer, bulletin board project, 514
message_from_string function
news gathering project, 461
messages table, bulletin board project
columns described, 502
creating, 501
__metaclass__ attribute
creating new-style classes, 206
finding out class of an object, 155
new-style/old-style classes, 175
old-style and new-style classes, 149
property function, 188
metaclass syntax, Python 3.0, 602, 605
metaclasses, 176
Metakit, 515
method resolution order (MRO), 156
see individual method names
arguments, 573
bound methods, 150
calling overridden version, 206
distinguishing methods from functions, 150
functions compared, 43
lists, 585
magic methods see magic methods
making method or attribute private, 151
MatchObjects, re module, 248
method definitions, 149
object-oriented design, 157, 158
overriding in subclasses, 148, 156
polymorphism and, 143
mhlib module, 310
microthreads, 312
minimum field width, string formatting, 56, 57, 59
mix-in classes, 159
dispatcher mix-in classes, 444–446
mktime function, time module, 233, 234
mod_python framework, 336–343, 347
configuring Apache, 338
installing, 337
publisher handler, 336, 341–343
mode argument, open function (files), 261–263
modulator tool, 371
modules, 29, 209–221, 259, 576
see individual module names
__all__ variable, 219
“batteries included” phrase, 221
checking if module exists, 218
creating and locating, 209–210
defining functions in, 212–214
dir function, 218
extinct modules in Python 3.0, 604
import statement, 209
import-only-once behavior, 211
magic methods, 576
main purpose of, 210
making code reusable, 212
making modules available, 214–216
making programs available as, 212
mapping, sys module, 222
modifying sys.path to specify location, 210, 214
naming file containing module code, 217
newly released third-party modules, 7
packages, 259
packaging in packages, 217
packaging in Python 3.0, 604
permissions affecting save location, 214
putting modules in existing sys.path, 214–215
reasons for not doing, 215
py_modules directive, Distutils, 386
pyc file extension, 210
reading source code, 221
reloading, 211
renamed modules in Python 3.0, 604
specifying module location in PYTHONPATH, 215–216
standard library modules, 221–259
switching between database modules, 294
test code contained in, 259
third-party modules, 597
wrapping modules as archive file, 386–387
writing extension modules for Python, 370
modulo operator
list comprehension, 105
string formatting, 66
modulus operator, 11
mouse cursor
pygame.mouse module, 550
mouse module, pygame, 550
move method, rectangles, 555
MRO (method resolution order), 156
μTidyLib, 324
multiple connections
multiple inheritance, 156, 575
multiple superclasses, 155–156
multiplication operator, 37, 580
mutable objects see immutability
mxTidy, 324
MySQL database
bulletin board project, 500, 501
MySQLdb module, 597
bulletin board project, 500
name variable, testing modules, 213
name argument, open function (files), 261
named arguments, 572
named value, Python DB API, 295
NameError class, 162
namespaces
see also scopes
class statement, 149
number of namespaces, 131
naming conventions
classes, 148
making method or attribute private, 152
initialization functions, 380
object-oriented design, 158
symbolic constants, 396
variables, 13
wx module methods, 281
nan value, 18
negative numbers
sqrt function, 18
nested scopes, 133
instant markup project, 410
nesting blocks, if statements, 91
Network News Transfer Protocol see NNTP
network programming
asynchronous I/O with select and poll, 313–316
chat server project, 469
event-driven networking framework, 316
firewalls, 305
forking and threading with SocketServer, 313
introduction, 305
opening remote files, 308
port numbers, 307
retrieving remote files, 309
sockets, 470
synchronous network programming, 306
newline character
changes on opening in text mode, 262
platforms using other line separators, 267
NEWNEWS command
NNTP server supporting, 454, 456
newnews method, NNTP class, 455, 456
news gathering project, 453–468
automatically generated news page, 461
downloading messages from newsgroups, 455
flexible news-gathering agent, 463
further exploration, 467
goals, 454
NewsAgent class, 459
news page with more than one source, 463
tools, 454
newsgroups
downloading messages from, 455
online resources, 597
NewsItem class
news gathering project, 459
newsreaders see NNTP clients
__next__ method, 192
changes in Python 3.0, 606
iter method returning iterator, 192, 207
object implementing, 193
nextfile function, fileinput module, 226
finding sender of e-mail, 253
nextset method, cursors, 297
nextState method, LevelCleared class
arcade game project, 564
nlargest function, heapq module, 230, 231
NNTP (Network News Transfer Protocol), 453
NNTP class
instantiating, 455
NNTP clients, 453
NNTP constructor
connecting to servers, 454
NNTP servers
'211' string beginning, 455
'411' string beginning, 455
connecting to servers, 454
description, 453
downloading messages from newsgroups, 455
main network of, 453
news gathering project, 454
nntplib library
news gathering project, 453, 454, 455
nntplib module, 310
NNTPSource class
news gathering project, 461, 462
Node class, GUI client project, 541
Node class, XML-RPC file sharing project, 520, 530
broadcast method, 521, 522, 525, 532
constructor, 520
fetch method, 520, 521, 524, 531
handle method, 521, 522, 525, 531
hello method, 520, 521, 524, 531
query method, 520, 521, 522, 524, 530
stopping and restarting node, 527
None value, 37
changes in Python 3.0, 605
return value, functions, 117
using None as placeholder, 574
None value, Boolean values, 89
nongreedy patterns see greedy patterns
nonlocal keyword, 133
nonzero method, 182
nose
alternatives to unit test tools, 355
not equal to operator, 580
not in operator, 580
NotImplementedError exception, 224
NotSupportedError exception, 295
nsmallest function, heapq module, 230, 231
NUMBER value, Python DB API, 298
numbered iteration, 101
complex numbers, 18
floating-point numbers, 10
hexadecimal numbers, 12
imaginary numbers, 18
immutability, 119
nan value, 18
numbers containing leading zeros, 70
octal numbers, 12
numeric arrays
analyzing many forms of numeric data, 370
numeric value, Python DB API, 295
%o conversion specifier, 56
object function, 583
object-oriented design, 157–158, 159
object-oriented languages, 141
Smalltalk, 151
object-oriented programming see OOP
accessing attributes of objects, 150–152
checking if object has specific attribute, 172
classes and objects, 147
deleting, 107
exception objects, 161
finding out class of an object, 155
inheritance, 575, 147–154, 155
MatchObjects, re module, 247
methods, 573
object-oriented design, 157
forms of, 144
methods and, 143
private attributes, 151
referencing not owning, 376
referring to the object itself, 149
seeing all values stored in objects, 157
treating objects as abstract, 146
objects.py file, arcade game project, 556, 557
oct function, 583
octal literals, Python 3.0, 606
octal numbers, 12
Official Python Distribution, 595
offset parameter
seek method, files, 266
OnInit method, Client class
GUI client project, 538, 539, 541, 543
online chatting see chat server project
OOP (object-oriented programming)
distinction between types and classes, 148
encapsulation, 141, 145–147, 158
inheritance, 141, 147–154, 155, 159
polymorphism, 141, 142–145, 158
forms of, 144
summary of key concepts, 158–159
open function, files, 261–263, 275
binary mode, 262
buffering argument, 263
name argument, 261
open function, import statement, 85
open function, shelve module, 238
open function, webbrowser module, 225
opent function, 583
operating systems
OperationalError exception, 295
operations
adding, 37
strings, 53
tuples, 50
operator module
add function, 144
operators
* (parameter splicing) operator, 126, 127
** (keyword splicing) operator, 128
+= operator, 522
adding sequences, 37
arithmetic operators, 9
conditional operator, 96
distributing operators, 128–129, 604
double slash operator, 10
exponentiation operator (**), 11
gathering operators, 125–128, 602, 603, 604, 606
logical operators, 96
membership operator, 94
modulo operator, 66
modulus operator, 11
multiplying sequences, 37
repetition operators, 250
splicing operators, 129
string formatting operator, 53
ternary operator, 96
optimization
extending Python for speed, 365–366
optparse module, 259
levels of configuration, 398
news gathering project, 468
or operator
Boolean operators, 96
short-circuit logic, 574
operator precedence, 579
finding union of two sets, 228
functions and variables, 223
makedirs function, 447
os.path module, XML parsing project, 447
outer scope see global scope
output
stdout stream, sys module, 222
overriding
description, 206
getitem method, 186
methods and constructors, 177–179
calling unbound superclass constructor, 179–180
methods in subclasses, 148, 156
package manager
installing Python on Linux/UNIX, 4
announcing/publishing, 390
centralized index of, 390
description, 259
distributing, 383
files and directories layout, 217
graphics-generating package, 426
grouping modules in, 217
making Python recognize, 217
module packaging in Python 3.0, 604
Python Package Index, 384
packaging programs
creating Linux RPM packages, 387
creating Windows installer, 387
distribution formats, 387
introduction, 383
wrapping modules as archive file, 386–387
page element, XML parsing project, 437, 442
painting pretty picture project see graphics creation project
palindrome module
hand-coded using Python/C API, 379–380
palindromes, 372
Panel class, wx module see wx.Panel class
ParagraphRule class
instant markup project, 417, 421
Python 3.0, 602, 603, 604, 606
parameters, functions, 16, 117–130
actual parameters, 118
arguments, 118
collecting parameters, 125–128
combining positional/keyword parameters, 124
default values, 124
description, 139
distributing operators, 128–129, 604
examples using parameters, 129–130
formal parameters, 118
gathering operators, 125–128, 602, 603, 604, 606
immutability, 123
keyword parameters, 123–125, 602, 606
keyword-only parameters, 602, 606
local naming, 120
local scope, 118
modifying parameters, 123
passing parameters to functions, 572
positional parameters, 123
default values, 124
rebinding parameters, 123, 572
self parameter, 150
values, 118
paramstyle property, Python DB API, 294, 295
parent argument, wx constructors, 281
parse function, xml.sax module, 439
parse method, instant markup project, 414
Parser class, instant markup project, 413–415, 421
parse method, 414
parsers, instant markup project, 409, 413–415
parsing XML project see XML parsing project
parsing, HTML, 322
HTMLParser class/module, 325–327
partition method, strings, 587
pass statements, 107, 112, 590
passthrough variable
XML parsing project, 448
password handling, 494
password parameter
connect function, Python DB API, 296
passwords
bulletin board project, 503
path configuration files, 216
path submodule, os module, 223, 447
path variable, sys module, 222
modifying to specify module location, 210, 214
putting modules in existing sys.path, 214–215
reasons for not doing, 215
search path (list of directories), 214
using PYTHONPATH alongside, 216
pathsep variable, os module, 223, 224
patterns
greedy patterns, 250
re module functions, 245
Paused class, arcade game project, 561
PDF (Portable Document Format) files
editing, 425
getting PDF reader, 425
graphics creation project, 425
pdfgen module, ReportLab package, 427
PDFs, drawing with ReportLab, 427
peer-to-peer file sharing
GUI client project, 544
MAX_HISTORY_LENGTH constant, 522
XML-RPC file sharing project, 517–535
peer-to-peer systems, 517
performance
join method, strings, 255
using CGI handler, 339
period (dot) character
regular expression wildcards, 242
permissions
dynamic web pages with CGI, 329–330
saving modules, 214
Pilgrim, Mark, 345
pipe characters, 265
placeholders
using None as placeholder, 574
PlainDestination class
news gathering project, 460, 462
plain-text markup, 403
markup systems, 424
platform variable, sys module, 222
platforms, GUI, 277
Platypus, ReportLab package, 434
playful programming, 393
Plone, 344
poll function, select module, 320
asynchronous I/O with, 315–316
poll object
register/unregister methods, 315
POLLXYZ events
polling event constants in select module, 315
PolyLine class
constructing PolyLine objects, 429
duck typing, 145
forms of, 144
interfaces, 156
isinstance function or, 155
methods and, 143
repr function, 145
subclassing list/dict/str types, 185
types, 145
use of isinstance function, 185
pop functions
pop method, dictionaries, 79, 586
popen function, 224
running Tidy, 324
sequence unpacking, 86
poplib module, 310
port numbers
chat server project, 470, 471, 473
network programming, 307
numbers requiring administrator privileges, 470
pos argument, wx.Button constructor, 283
positional parameters
combining with keyword parameters, 124
default values, 124
description, 123
gathering operators, 125–128, 602, 603, 604, 606
keyword-only parameters, 602, 606
POST method
getting information from CGI script, 335
remote editing with CGI project, 490
PostgreSQL database
bulletin board project, 500, 501
dynamic web pages with CGI, 329
power (exponential) operator, 11
power function, 135
powers
recursive function to calculate, 135
pprint function, 215
precedence, operators, 579–581
precision, string formatting, 54, 56, 57
preparations for projects
structure of projects in this book, 402
print function, Python 3.0, 605
print statement
changes in Python 3.0, 600
print statements, 14, 111, 590
printable constant, string module, 60
printing
pretty-printing function, 215
using arguments in reverse order, 223
priority queues
private attributes, 151
problem descriptions for projects
structure of projects in this book, 401
procedures
functions without return values, 117
remote procedure calls
REST and RPC, 346
SOAP, 346
with Pyro, 346
XML-RPC, 345
hotshot/profile/timeit modules, 363
programming
see also OOP (object-oriented programming)
algorithms, 9
books about programming, 400–401
built-in functions, 16, 581–584
comments, 22
configuration, 394, 396–398, 401
dictionary methods, 74–80, 585–586
functional programming, 138–139, 140
functions, 16
literal values, 579
making scripts behave like programs, 20–22
minimum requirements, 400
playful programming, 393
pseudocode, 136
requirement specification, 350–351
saving and executing programs, 19–20
string methods, 60–66, 586–588
symbolic constants, 396
test-driven programming, 349–352, 364
testing, 394
text editor, 19
variables, 13
ProgrammingError exception, Python DB API, 295
programs
abstraction and program structure, 114
building Windows executable programs, 383
creating executables with py2exe, 389–390
description, 29
importing programs as modules, 209
making programs available as modules, 212
packaging, 383
projects
bulletin board project, 499–515
graphics creation project, 425–434
instant markup project, 403–424
news gathering project, 453–468
remote editing with CGI project, 489–498
structure of projects in this book, 401
XML-RPC file sharing project, 517–535
properties
accessor methods defining attributes, 187–188
creating properties, 188
__getattr__/__setattr__ methods, 191–192
implementing with old-style classes, 191
introduction, 175
new-style/old-style classes, 175
property function, 188–189, 207, 583
calling with arguments, 189
descriptor protocol, 189
__get__/__set__ methods as attributes of, 188
magic methods, 189
new-style/old-style classes, 206
proportion argument
Add method, wx.BoxSizer class, 285
protocol attribute, Factory class
writing Twisted server, 317
protocol module, 317
protocols, 182
descriptor protocol, 189
sequence and mapping protocol, 182–185
case against rewriting, 395
extending Python for improved speed, 365
PSP (Python Server Pages), 339
PSP tags, 340
psp file name extension, 340
PSP handler, mod_python, 336, 339–341
Psyco, 370
psycopg module, 597
bulletin board project, 500
pth file extension, 216
publisher handler, mod_python, 336, 341–343
pump function, arcade game project, 550
punctuation constant, string module, 60
push functions
heappush function, 230
push method, chat server project, 475, 479
PuTTY software, 471
py file extension, 576
naming file containing module code, 217
running CGI script, 339
py.test
alternatives to unit test tools, 355
Py_BuildValue function, 378, 381
Py_INCREF macro, 376, 378, 381
py_modules directive, Distutils, 386
Py_None object, 378
py2exe extension
building Windows executable programs, 383
Inno Setup installer, 388
PyArg_ParseTuple function, 378, 381
PyArg_ParseTupleAndKeywords function, 378, 381
pyc file extension, 210
pychecker/pylint commands, 360
PyChecker/PyLint tools, 359–362, 364
PyCXX, 371
pyformat value, Python DB API, 295
Pygame documentation, 547
pygame modules, functions of
blit, 549
Font, 550
load, 551
pump, 550
set_caption, 549
set_visible, 552
Surface, 548
Pygame tool, arcade game project, 548–551
catching Pygame-specific errors, 549
pygame.display module, 549, 552
pygame.font module, 550
pygame.image module, 551
pygame.locals module, 549
importing constants from, 552
pygame.sprite module, 550
pylab, Matplotlib, 434
PyObject type, 377
PyPI (Python Package Index), 384, 390, 596
PyPy, 370
SIP tool, 371
Pyrex, 370
Pyro
remote procedure calls with, 346
pyRXP
dealing with XML in Python, 439
PySimpleApp class, wx module see wx.PySimpleApp class
downloading and installing, 299
Python
see also programming
adding line numbers to script, 227
alternative distributions, 5–7
built-in functions, 16, 581–584
cmath module, 18
comments, 22
converting values to strings, 24
creator of, 19
dictionary methods, 74–80, 585–586
distinction between types and classes, 148
enabling interoperability Python/C++, 371
extension approaches, 380
functional programming, 140
functions, 117
GUI platforms for, 291
GUI toolkits, 597
IDEs for Python, 6
IDLE interactive Python shell, 2
including C/C++ directly in Python code, 370
installing Python on Linux/UNIX, 3–5
installing Python on Macintosh, 5
interpreter, 9
just-in-time compiler for, 370
large integers, 12
literal values, 579
making scripts behave like normal programs, 20–22
popular GUI Toolkits for, 277
private attributes, 151
release information, 7
RPython, 370
running scripts from command prompt, 20
Stackless Python, 312
string methods, 60–66, 586–588
third-party modules, 597
web application frameworks, 343
web tutorial, 569
writing extension modules for, 370
abstract classes, 601
argument splicing, 604
automatic refactoring tool (2to3), 599
class decorators, 601
comparing incompatible types, 604
console I/O, 600
dictionary comprehension, 603
dictionary views, 603
extinct functions, 604
extinct modules in, 604
function annotation, 601
inequality operator, 604
integer division, 604
iterable unpacking, 603
iterator return values, 603
keyword-only parameters, 602, 606
metaclass syntax, 602
module packaging in, 604
new features in, 605
nonlocal variables, 602
renamed modules in, 604
set comprehension, 603
set syntax, 604
sources of information for, 606
standard library, 604
string formatting, 600
strings/bytes/encodings, 599
transitioning from older code to, 599
Python/C API
creating built-in types and classes, 378
deallocating objects, 376
extending Python using, 375–380
format strings, 378
framework for extensions, 377–378
hand-coded palindrome module, 379–380
writing extension modules for Python, 370
Python Cookbook, 596
Alex Martelli, 96
Python Database API (Python DB API), 294–298
apilevel property, 294
bulletin board project, 502, 503
constructors and special values, 297
exceptions, 295
switching between database modules, 294
threadsafety property, 294
Python distributions online, 595
Python documentation online, 596
Python eggs, 384
Python Enhancement Proposals, 596
Python extensions, 380
Python help (pyhelp.cgi), 596
“Python Imaging Library not available” warning, 429
Python interpreter
extending and embedding, 596
Python library reference, 596
Python Package Index see PyPI
Python reference manual, 596
Python Server Pages see PSP
Python web site, 595
PythonDebug directive, 339, 340
Python/C API reference manual, 596
PYTHONPATH environment variable, 215–216, 224, 225
Pythonwin environment, 6
PythonWin GUI toolkit, 278, 597
PyXML module, 597
installing, 437
qmark value, Python DB API, 295
importing data into databases, 302
-Qnew command-line switch, 10
Qt platform, PyQt GUI toolkit, 278
query method, Node class
XML-RPC file sharing project, 520, 521, 522, 524, 526, 530
queues
QUIT event
arcade game project, 552
quit function, servers, 457
Quixote, 344
quote/quote_plus functions, urllib module, 309, 320
quotes
%r conversion specifier, 57
raise statement, exceptions, 162–163, 173, 591
changes in Python 3.0, 605
raising exceptions, 161–163, 173
raising exceptions again, 164–165
random access, files, 266
random data
urandom function, 224
random function, random module, 235
random library
choice function, 144
choice function, 159
randomString function
XML-RPC file sharing project, 528, 532
randrange function, random module, 235, 236
range function, 99, 100, 101, 112, 583
raw_input
compared to input, 26
raw_input function, 30, 570, 583
changes in Python 3.0, 600, 606
ignoring return value, 238
reading strings, 113
rawDataReceived event handler, 318
RDF (Resource Description Framework), 345
RDF Site Summary, 345
see also regular expressions
compile function, 245
findall function, 245, 246, 252
finding sender of e-mail, 251–253
flags parameter, 247
functions, 245
VERBOSE flag, 249
sample template system, 253–257
screen scraping, 321
search function, 245
sub function, 245, 247, 249, 250
using group numbers in substitution string, 249
reactor module
listenTCP function, 318
read method, files, 264
examples using file methods, 268
iterating over file contents with, 270
reading entire file before iterating, 271
read mode, open function (files), 262
closing files after reading, 267
reading lines, files, 266, 274
readline method, files, 266
examples using file methods, 269
iterating over file contents with, 271
readlines method, files, 266
examples using file methods, 269
reading entire file before iterating, 271
xreadlines method and, 272
rebinding
global variables, 132
local and global scopes, 131, 132
variables in outer scopes, 133
receiveItems method, NewsAgent class, 459
rect attribute, Sprite class, 554
rectangle objects
clamp method, 556
move method, 555
infinite recursion, 134
parts of recursive function, 134
recursive definitions, 134
binary search example, 136–138
calculating factorials example, 134
calculating powers example, 135
value of, 136
recursive generators, 196, 197
recv method, socket class, 307
reduce function, 139, 140, 583
reduce method, set type, 229
refactoring
2to3 (automatic refactoring tool), 599
news gathering project, 453
reference counting
deallocating objects, 376
decrementing reference count, 376
extending Python using Python/C API, 376–377
garbage collection, 377
incrementing reference count, 376
references
Python library reference, 596
Python reference manual, 596
Python/C API reference manual, 596
REFERENCES keyword, PostgreSQL
CREATE TABLE command, 501
register command, Distutils, 390
register method, poll object, 315
register_function method
SimpleXMLRPCServer class, 519
register_instance method
SimpleXMLRPCServer class, 519, 523
regular expressions
see also re module
character sets, 243
denoting beginning/end of string, 244
description, 242
escaping special characters, 242
findall method, news gathering project, 462
finding sender of e-mail, 252
instant markup project, 409, 411
making readable, 249
repeating patterns, 244
sample template system, 253–257
screen scraping, 322
specifying alternative matches, 243
transforming into pattern object, 245
wildcards, 242
relational databases
tutorial/reading on, 293
release information, 7
modules, 211
replacing functionality using exec, 211
remainder operator, 580
remote editing with CGI project, 489–498
controlling file access, 493
debugging, 490
further exploration, 497
preparations, 490
requirements, 489
running the editor, 496
save.cgi script, 492, 494–495, 496
tools, 490
view.cgi script, 497
remote procedure calls see RPC
remove method, chat server project, 479
remove method, set type, 229
renderPDF class
drawToFile method, 428
RenderUpdates class
repetition operators, 250
replace method, strings, 63, 587
reply_to column, messages table
bulletin board project, 502, 504, 506
edit.cgi script, 510
testing, 513
view.cgi script, 508
reportlab module, 597
graphics package, 427
importing, 426
ReportLab package
constructing PolyLine objects, 429–430
description, 425
documentation for, 426
downloading, 426
first prototype for sunspots_proto.py, 430–431
pdfgen module, 427
Platypus, 434
reasons for choosing, 426
repr function, 25, 30, 573, 583
polymorphism, 145
representational state transfer (REST), 346
requirement specification
functional requirements, 350
test-driven programming, 350–351
reset method, Weight class
arcade game project, 558
Resource Description Framework (RDF), 345
resources
online resources, 595
Python 3.0, 606
REST (representational state transfer), 346, 535
reStructuredText, 424
return statement, 116, 572, 590
ending functions, 117
infinite recursion, 134
return value, functions, 16
functions without return values, 117
iterator return values, Python 3.0, 603
return value is None, 117
caution using if statements, 117
reverse argument of sort method, lists, 49
reverse function, 223
reverse method, lists, 46, 585
reversed function, 47, 52, 102, 112, 223, 583
reversed iteration, 102
rewriting
case against rewriting, 395
rfind method, strings, 587
Rich Site Summary, 345
right shift operator, 580
rindex method, strings, 587
rjust method, strings, 588
robotparser module, 310
rollback method, connections, 296
Room class, chat server project, 481
rooms, chat server project, 478–480
LoginRoom class, 479
LogoutRoom class, 479
main chat room, 479
Rossum, Guido van, 278
rounding, division, 16
rowcount attribute, cursors, 297
ROWID value, Python DB API, 298
rpartition method, strings, 588
RPC (remote procedure calls)
REST and RPC, 346
SOAP, 346
XML-RPC, 345
rpm format
bdist command, Distutils, 387
RPMs
creating Linux RPM packages, 387
XML parsing project, 437
RPython, 370
rsplit method, strings, 588
RSS (Really Simple Syndication), 345
RSS feeds, 345
client program handling feeds, 345
Scrape ’N’ Feed, 328
Universal Feed Parser, 345
rstrip method, strings, 227, 588
Rule class/object, instant markup project, 413, 419
condition/action methods, 412, 414
rules, instant markup project, 409, 412–413, 415–418
run function, reactor module, 318, 320
run method, Game class
arcade game project, 565
run method, profile module, 363, 364
runDefaultSetup function
news gathering project, 462
%s conversion specifier, 54
safe_substitute method, 55
sample function, random module, 235
save function, event handler, 286
save.cgi script
bulletin board project, 507, 511–513
remote editing with CGI project, 492, 494–495, 496
SAX (Simple API for XML), 435
dealing with XML in Python, 439
XML parsing project, 435, 438, 442
sax module, xml
parse function, 439
SAX parser
XML parsing project, 436
say command, chat server project, 480, 485
see also namespaces
class scope variable, 153
description, 140
global scope, 131
local scope, 131
parameters, 118
nested scopes, 133
instant markup project, 410
number of scopes, 131
rebinding global variables, 132
Scrape ’N’ Feed, 328
scraping see screen scraping
Beautiful Soup module, 327–328
HTMLParser callback methods, 325
using HTMLParser module, 325–327
XHTML, 325
scripts
adding line numbers to, 227
behaving like normal programs, 20–22
running from command prompt, 20
saving and executing programs, 19–20
scroll bars, text controls, 284
sdist command, Distutils, 386, 387
formats switch, 387
search function, re module, 245
second implementations of projects
structure of projects in this book, 402
second system syndrome
case against rewriting, 395
security
CGI security risks, 330
password digests, 494
PythonDebug directive, 340
using exec and eval, 109
seek method, files, 266
select function, select module
asynchronous I/O, 312, 314–315
avoiding forking and threading, 312
description, 320
select module, poll function
polling event constants in select module, 315
self parameter
calling unbound superclass constructor, 180
class methods, 189
class statement, 149
distinguishing methods from functions, 150
framework for extensions, 377, 378
static methods, 189
send method, generators, 198
send method, socket class, 307
sender column, messages table
bulletin board project, 502
sep variable, os module, 223, 224
separators
altsep variable, 224
linesep variable, 224
sequence unpacking
file iterators, 274
popitem method, 86
sequences, 31–40, 51, 182, 206
accessing individual elements, 32
accessing ranges/slices of elements, 34
adding, 37
arithmetic sequence, 184
built-in sequence types, 31
close function, 226
comparing, 95
concatenating, 37
creating infinite sequence, 183
deleting element associated with key, 182
empty lists, 37
finding number of elements in, 40
finding smallest/largest elements in, 40
immutable sequences, 49
illegal type of index used, 184
initialization, 37
iterating over, 32
key is negative integer, 183
making from iterators, 194
returning number of elements contained in, 182
returning value of key, 182
simulating, 185
specifying step length between elements, 36
storing value for key, 182
SERIAL keyword, PostgreSQL
CREATE TABLE command, 501
serve_forever method
SimpleXMLRPCServer class, 519, 523
server sockets, 319
ServerProxy class
XML-RPC file sharing project, 520
servers
connecting to, 454
forking server, 313
SocketServer-based servers, 317
threading server, 313
writing Twisted server, 317–319
service provider, web services, 344
service requester, web services, 344
Set class instances, 228
set comprehension, Python 3.0, 603
set function, 584
set type
add method, 229
frozenset type and, 229
immutability, 229
reduce method, 229
remove method, 229
sets module and, 228
set_caption function, arcade game project, 549
set_mode function, arcade game project, 549, 552
set_reuse_addr method, chat server project, 473
set_terminator method, chat server project, 473, 475
set_visible function, arcade game project, 552
setattr function, 157, 159, 584
setdefault method, dictionaries, 79, 106, 586
setdefaultencoding function, sys module, 451
Setext, 424
setinputsizes method, cursors, 297
__setitem__ method, 182
setName method, private attributes, 151
setoutputsize method, cursors, 297
empty set, 604
new syntax in Python 3.0, 604
SetSizer method, wx.Panel class, 284
setup function, Distutils, 384, 391
setup script, Distutils, 383, 384
setup.py script, Distutils, 384, 385, 387
commands to run setup.py, 390
setuptools project, 384
SetValue method
load event, wxPython, 286
sgmllib module, 322
sha module, 343
remote editing with CGI project, 494
shadowing
locals function, 132
shallow copy, dictionaries, 75
shebang, 21
modifying objects, 239
open function, 238
shift operator precedence, 580
short-circuit logic, Boolean operators, 96, 574
Show method, wx.Frame class, 281
shuffle function, random module, 235
signs (+/-), string formatting, 58
Simple API for XML see SAX
simple generators see generators
Simple Wrapper and Interface Generator see SWIG
simple_main.cgi script
bulletin board project, 505
SimpleWebSource class
news gathering project, 462
SimpleXMLRPCServer class, 519
allow_reuse_address attribute, 527
register_function method, 519
register_instance method, 519, 523
registering Node with, 521
serve_forever method, 519, 523
SimpleXMLRPCServer module, 310, 518
SIP tool, 371
site-packages directory
executing path configuration files, 216
putting modules in existing sys.path, 215
size argument, setting button positions using, 283
BoxSizer class, 284
layout mechanisms, 291
using relative coordinates, 284
Slashdot, 499
sleep function, time module, 233, 234
slice function, sequences, 185
slicing
precedence, 580
simulating, 185
Smalltalk, 151
SmartASCII, 424
smtpd/smtplib modules, 310
SOAP/SOAPy, 346
socket class, socket module, 306
accept method, 306
bind method, 306
connect method, 306
gethostname function, 306, 307
listen method, 306
recv method, 307
send method, 307
socket class, 306
tools for chat server project, 470
socket server
connecting to, 470
sockets
chat server project
bind method, 471
create_socket method, 471, 472
datagram socket, 306
description, 319
network programming, 470
stream socket, 306
types of, 306
SocketServer framework, 319
BaseRequestHandler class, 311
classes, 311
forking and threading with, 313
SocketServer-based servers, 317
StreamRequestHandler class, 311
sort command, files, 265
sort method, lists, 47–49, 585
cmp built-in function, 48
key argument, 48
keyword arguments, 48
reverse argument, 49
sorted function, 48, 52, 102, 112, 584
keyword arguments, 49
sorted iteration, 102
Sorting Mini-HOWTO, 49
Andrew Dalke, 49
source code
encoding in Python 3.0, 605
exploring modules, 221
source code checking, 359
PyChecker/PyLint tools, 359–362, 364
SourceForge, 596
span method
MatchObjects, re module, 248
special attributes see magic attributes
special characters
character sets, regular expressions, 243
escaping, regular expressions, 242
special methods see magic methods
special values, Python DB API, 297, 304
speed
extending Python to improve, 365–366
splicing operators, 129
argument splicing, Python 3.0, 604
split function, re module, 245, 246
split method, strings, 63, 588
food database application, 300
splitlines method, strings, 588
Sprite class, pygame.sprite module
arcade game project, 550
image attribute, 554
rect attribute, 554
sprite module, pygame, 550
SQL
tutorial/reading on, 293
bulletin board project, 500
creating database in, 501
conversions between numbers and strings, 303
stack trace
catching exceptions, 167
exceptions and functions, 170
Stackless Python, 312
alternative Python distributions, 6, 7
stacks, 45
standard library modules, 221–259
see individual modules
opening/closing standard library files, 221
Python 3.0, 604
StandardError exception, Python DB API, 295
starred iterable unpacking, 603, 606
start method
MatchObjects class, 248
Node class, 523, 524, 528, 531
startElement event handler
XML parsing project, 440, 441, 445
startfile function, os module, 225
startPage method
XML parsing project, 448
startswith method, strings, 588
StartUp class, arcade game project, 564
startUp method, test fixture, 356
state, encapsulation, 147
State class, arcade game project, 559
state variables
screen scraping using HTMLParser, 326
assertions, 111
assignment statements, 85–88, 111, 589
compared to expressions, 13
conditional statements, 88–97, 111
assertions, 97
elif clause, 91
else clause, 90
if statement, 90
nesting blocks, 91
del statement, 41, 107–108, 112, 590
deleting objects, 107
description, 29
doing nothing, 107
exec statement, 109–110, 112, 592
expression statements, 589
for statement, 593
function definition statement, 115, 594
global statements, 592
import statements, 84–85, 111, 591
for loop, 99
using else clause in, 105
while loop, 98
try statements, 593
while statement, 592
while True/break idiom, 104–105
yield statement, 590
self parameter, 189
staticmethod function, 584
stderr stream, sys module, 222, 263
stdin stream, sys module, 222, 263
file iterators, 273
script counting words in, 265
stdout class
write method, 318
stdout stream, sys module, 222, 263
StopIteration exception, 192
store function, 122
str type, Python 3.0, 600, 605
stream redirection functionality
changes in Python 3.0, 600
stream socket, 306
StreamRequestHandler class, 311
streams, chat server project, 477
strftime function, time module, 233, 455, 456
String constructor
drawing with ReportLab, 428
string formatting
changes in Python 3.0, 600, 605
string methods, 60–66, 586–588
capitalize, 586
center, 586
count, 586
decode, 586
encode, 586
endswith, 586
expandtabs, 586
index, 587
isalnum/isalpha/isdigit, 587
islower/isspace, 587
ljust, 587
lstrip, 587
partition, 587
rfind, 587
rindex, 587
rjust, 588
rpartition, 588
rsplit, 588
safe_substitute, 55
splitlines, 588
startswith, 588
substitute, 55
swapcase, 588
zfill, 588
string module, 55
constants, 60
String type, 579
STRING value, Python DB API, 298
StringIO, Python 3.0, 605
changing to lowercase, 62
comparing, 94
concatenating, 24
converting values to, 24
evaluating expression strings, 254
executing/evaluating on the fly, 108
finding substrings, 60
precision specifiers, 54
Python 3.0, 600
signs/alignment/zero-padding, 58
string formatting operator, 53
width and precision, 57
input compared to raw_input, 26
modulo operator, 66
non-english strings, 66
numbers containing leading zeros, 70
operations, 53
precedence, 581
Python 3.0, 599
removing whitespace, 64
repr function, 25
template strings, 55
using group numbers in substitution string, 249
strip method, strings, 64, 241, 588
food database application, 300
strptime function, time module, 233, 234
style parameter
wx.BoxSizer constructor, 285
wx.TextCtrl constructor, 283
sub function, re module, 245, 247
instant markup project, 407, 408, 409, 411
sample template system, 254
using group numbers in substitution string, 249, 250
sub method, Handler class
instant markup project, 410, 411
issubclass method, 154
overriding methods, 148, 156, 177
subclassing
subject column, messages table
bulletin board project, 502
subpatterns
finding sender of e-mail, 252
groups, re module, 247
subpatterns, regular expressions, 243–244
running Tidy, 324
using command-line tools, 360
substitute method, 55
substitutions
using group numbers in substitution string, 249
sunspots example
fetching data from Internet, 432
final sunspot program (sunspots.py), 433
first implementation, 431
first prototype, 430
introduction, 425
preparations, 426
second implementation, 434
using LinePlot class, 432, 434
super function, 180–181, 207, 584
changes in Python 3.0, 606
new-style/old-style classes, 175, 176, 206
subclassing list type, 186
using when multiple superclasses, 181
superclasses
calling unbound superclass constructor, 179–180
description, 147
multiple inheritance, 156
multiple superclasses, 155–156
overriding methods and constructors, 177
overriding methods in subclasses, 156
Surface function, arcade game project, 548
surface objects, 548
convert method, 554
swapcase method, strings, 588
SWIG (Simple Wrapper and Interface Generator), 371–375, 380
automating compilation, 375
-c++ option, 373
compiling, 373
Distutils using, 389
header file, 373
installing, 371
interface file, 373
linking, 374
program to recognize palindromes, 372–375
-python option, 373
running, 373
using Distutils, 375
using SWIG, 372
wrapping code, 375
example illustrating, 288
Jython and, 290
switches
command-line switches, 398
symbolic constants, 396
synchronous network programming, 306
SyntaxError exception, 163
sample template system, 254
functions and variables, 222
getdefaultencoding function, 451
path variable
modifying to specify module location, 210, 214
putting modules in existing sys.path, 214–215
search path (list of directories), 214
using PYTHONPATH alongside, 216
setdefaultencoding function, 451
sys.maxint, Python 3.0, 605
system function, os module, 223, 224
SystemRandom class, 234
tab characters, indenting with, 88
tables
CREATE TABLE command, 501
tags
HTMLParser callback methods, 325
tar command
compiling Python from sources, 4
tar files
sdist command, Distutils, 387
TCPServer class, SocketServer module, 311
tearDown method, test fixture, 356
tell method, files, 266
telnet command, chat server project, 470
telnetlib module, 310
Template class, string module, 55, 74
template strings, 55
terminator, chat server project, 473
ternary operator, 96
test code, modules, 259
test fixture, 356
TestCase class, unittest module, 355
instantiating all subclasses of, 356
test-driven programming, 349–352, 364
anticipating code changes, 351
automated tests, 351
key steps in process, 352
making code fail test, 352
requirement specification, 350–351
simple test program, 350
unittest module, 353
testing
alternatives to unit test tools, 355
anticipating code changes, 351
automated testing, 394
bulletin board project, 513
code coverage, 351
doctest module, 352, 353–355, 364
minimum requirements, 400
PyChecker/PyLint tools, 359–362, 364
requirement specification, 350–351
source code checking, 359
test-driven programming, 349–352, 364
unit testing, 349
unittest module, 352, 355–358, 364
testmod function, doctest module, 353, 354, 364
TeX typesetting program, 404, 426
text
text column, messages table
bulletin board project, 502
text controls
creating, 283
creating text area, 283
horizontal scroll bar, 284
multiline text area, 284
text editor
selecting for programming, 19
wxPython GUI toolkit building, 279–288
creating application object, 280
creating frames (windows), 281
creating widgets (components), 281
event handling, 286
finding file name, 286
importing wx module, 280
interface elements, 280
minimal requirements for text editor, 279
positions and sizes, 283
putting text into text area, 286
titles and labels, 282
text files
changes in Python 3.0, 600
changes on opening in text mode, 262
text parameter, CGI, 490
textAnchor argument, String constructor, 428
TextCtrl class, wx module see wx.TextCtrl class
Textile, 424
threading, 312
chat server project, options for, 469
microthreads, 312
multiple connections, 312
SocketServer module, 313
XML-RPC file sharing project, 528, 534
threading module
XML-RPC file sharing project, 519
threading server, 313
threadsafety property, Python DB API, 294
throw method, generators, 199
getting Tidy library, 324
μTidyLib, 324
mxTidy, 324
using command-line Tidy, 324
using HTMLParser, 325
Tidylib, 324
Time constructor, Python DB API, 298
time function, time module, 233, 234, 455
time module, 232–234, 259, 454
TimeFromTicks constructor, Python DB API, 298
Timestamp constructor, Python DB API, 298
TimestampFromTicks constructor, Python DB API, 298
TinyFugue, chat server project, 471
title argument, wx.Frame constructor, 282
title method, strings, 63, 588
title rules, instant markup project, 415
TitleRule class, instant markup project, 416, 420
Tk GUI toolkit, 289
Tk platform, Tkinter GUI toolkit, 277
Tkinter GUI toolkit, 277, 289, 597
choosing between GUI toolkits, 278
example illustrating, 288
toolkits see GUI toolkits
tools for projects
structure of projects in this book, 401
trace module, 258
trace.py program, 351
tracebacks, 161
cgitb module, 502
transactions, 296
translate method, strings, 60, 64–66, 588
translation tables, 65
trapping exceptions see catching exceptions
trees, 201
True value
Boolean values, 89
changes in Python 3.0, 605
while True/break idiom, 104–105
truth, Boolean values, 89
try statements, 593
try/except statements, 163–169, 576
catching all exceptions, 169
danger of, 167
catching exception object, 166
catching many exceptions in one block, 166
checking whether object has specific attribute, 172
combining try/except/finally/else, 170
finally clause, 170
trapping KeyError exception, 172
using more than one except clause, 165–166
try/finally statement, 169, 173
calling exit function in, 222
closing database, 241
closing files, 267
tuple parameter unpacking, Python 3.0, 606
conversion specifiers, 56
distributing operator, 128, 604
empty tuple, 49
fields of Python date tuples, 233
finding out if object is tuple, 142
immutability, 119
lists compared, 31
tuple operations, 50
uses of, 51
writing tuple with single value, 50
tutorial, Python, 569–577, 596
Twisted framework, 316–319, 320
chat server project, options for, 469
deferred execution, 317
downloading and installing, 317
remote procedure calls with, 346
SOAP toolkit, 346
web application frameworks, 344
writing Twisted server, 317–319
twisted.internet.protocol module
Factory class, 317
twisted.protocols.basic module
LineReceiver protocol, 318
txt2html, 424
type objects, 17
TypeError class, 163
inappropriate key type used, 183, 184
recursive generators, 196, 197
types, 569
see also classes
bool type, 90
conversion specifiers, 57
dictionary type, 69
duck typing, 145
polymorphism, 145
%u conversion specifier, 56
UDPServer class, SocketServer module, 311
unary operators, 580
unbound methods
calling unbound superclass constructor, 180
underscores
magic methods, 575
making method or attribute private, 151, 573
UnhandledQuery class
XML-RPC file sharing project, 528, 530
unichr function, 584
unicode function, 584
Unicode type, 579
changes in Python 3.0, 600, 605
uniform function, random module, 235
uninstall command, Distutils, 385, 388
union method, set type, 228, 229
unit testing, 349
alternatives to unit test tools, 355
unittest module, 352, 355–358, 364
distinguishing errors and failures, 357
test-first, code-later programming, 353
Universal Feed Parser, 345
universal newline support mode, files, 263
UNIX
installing mod_python on, 337
levels of configuration, 398
making executable script in, 576
setting environment variables, 216
UnixDatagramServer class, 311
UnixStreamServer class, 311
unknown method, chat server project, 479
Unofficial Planet Python blog, 597
unpacking
iterable unpacking, Python 3.0, 603
starred iterable unpacking, 603, 606
tuple parameter unpacking, 606
unquote function, urllib module, 309, 320
unquote_plus function, urllib module, 309, 320
unregister method, poll object, 315
update method, dictionaries, 80, 586
upper method, strings, 95, 588
uppercase constant, string module, 60
urandom function, os module, 224
urlcleanup function, urllib module, 309
urlencode function, urllib module, 309, 320, 334
urlfile.txt file, GUI client project, 540
news gathering project, 453
quote function, 309
quote_plus function, 309
screen scraping, 321
invoking CGI scripts without forms, 334
unquote function, 309
unquote_plus function, 309
urlcleanup function, 309
urlencode function, 309
urlopen function, 308, 309, 432
urlretrieve function, 309
urlopen function, urllib module, 308, 309, 320
graphics creation project, 432
urlparse module, 310
XML-RPC file sharing project, 519
urlretrieve function, urllib module, 309, 320
URLs filter
instant markup project, 418
urls.txt file
XML-RPC file sharing project, 534
Usenet, 453
Usenet groups, 597
user parameter
connect function, Python DB API, 296
UserList/UserDict/UserString
subclassing list/dict/str types, 185
users
getting input from users, 14–15
users dictionary, 479
util.py block generator
instant markup project, 406
ValueError class, 163
values
literal values, 579
None, 37
seeing all values stored in objects, 157
special values, Python DB API, 297, 304
values method, dictionaries, 80, 100, 586
changes in Python 3.0, 605
van Rossum, Guido, 278
all variable, 219
altsep variable, 224
environment variables, 216
global variables, Python DB API, 294–295
linesep variable, 224
modules mapping, 222
naming conventions, 13
nonlocal variables, Python 3.0, 602
path variable, 222
platform variable, 222
rebinding variables in outer scopes, 133
scopes, 140
stderr stream, 222
stdin stream, 222
stdout stream, 222
VERBOSE flag, re module functions, 249
version control
remote editing with CGI project, 497
versions, Python DB API, 294
view.cgi script
bulletin board project, 506, 508–510
link to edit.cgi, 508
testing, 513
remote editing with CGI project, 497
views
dictionary views, Python 3.0, 603
virtual tea party see chat server project VisualWx environment, 6
Warning exception, Python DB API, 295
warnings, 173
Weave, 370
web application frameworks, 343, 347
web development
web forms see forms
web pages
dynamic web pages with CGI, 328–336
adding pound bang (#!) line, 329
CGI script, 331
CGI security risks, 330
invoking CGI scripts without forms, 334
setting file permissions, 329–330
using cgi module, 333
Beautiful Soup module, 327–328
Tidy, 322
XHTML, 325
web programming
dynamic web pages with CGI, 328–336
Beautiful Soup module, 327–328
web server
dynamic web pages with CGI, 328–329
Web Service Description Language (WSDL), 345
remote procedure calls with XML-RPC, 345
RSS, 345
service provider, 344
service requester, 344
SOAP, 346
web sites
generating from single XML file, 435
XML parsing project, 437
web tutorial, Python, 569
web.py, 344
web-based bulletin board see bulletin board project
webbrowser module, 225
website element, XML parsing project, 437
website.py file, XML parsing project, 448
website.xml file, XML parsing project, 438
WebsiteConstructor class, 449, 451
Weight class, arcade game project, 558
weight.png file, arcade game project, 554, 556
weight.pny file, arcade game project, 554
whence parameter
seek method, files, 266
ignoring return value of raw_input function, 238
iterating over file contents with read(), 270
iterating over file contents with readline(), 271
while statements, 592
while True/break idiom, 104–105
iterating over file contents with read(), 271
whitespace
handling for DOS, 225
VERBOSE flag, re module functions, 249
who command, chat server project, 480, 485
widgets
wxPython GUI toolkit creating, 281
widgets, text editor
Bind method, 286
width of field, string formatting, 56, 57, 59
WikiCreole, 424
WikiMarkupStandard, 424
wikis
remote editing with CGI project, 489
wiki-style markup systems, 424
Wikitext, 424
wildcards, regular expressions, 242
Windows
installing mod_python on, 337
setting environment variables, 216
windows see frames
Windows Installer file, 3
Wingware environment, 6
wininst format
bdist command, Distutils, 387, 388
with statement, 267
changes in Python 3.0, 605
context managers, 268
with statements, 593
wrapper code
wrapping legacy code, 366
wrapping modules as archive file, 386, 387
write method
save event, wxPython, 286
write method, stdout class
writing Twisted server, 318
write mode, open function (files), 262
writeback parameter, shelve.open function, 239
writeFooter method
XML parsing project, 446, 448, 451
writeHeader method
writelines method, files, 267, 269
XML parsing project, 451
closing files after writing, 267
updating files after writing, 268
writing lines, files, 266, 274
WSDL (Web Service Description Language), 345
wx module
importing, 280
method naming conventions, 281
style facets, 284
using keyword arguments with wx constructors, 282
wx.ALL flag, 285
wx.App class
creating application object, 280
GUI client project, 538
MainLoop method, 281
wx.BoxSizer class
Add method, 285
building text editor, 284
horizontal or vertical style, 285
style argument, 285
using relative coordinates, 284
wx.Button class
adding button to frame, 281
label argument, 282
parent argument, 281
pos (position) argument, 283
size argument, 283
wx.EVT_BUTTON symbolic constant, 286
wx.EXPAND flag, 285
wx.Frame class
building text editor, 281
parent argument, 281
Show method, 281
size argument, 283
title argument, 282
windows as instances of, 281
wx.HORIZONTAL/wx.VERTICAL values, 285
wx.HSCROLL value, 284
wx.LEFT/wx.RIGHT flags, 285
wx.Panel class
building text editor, 284
SetSizer method, 284
wx.PySimpleApp class
creating application object, 281
wx.TE_MULTILINE value, 284
wx.TextCtrl class
building text editor, 283
style parameter, 283
wx.TOP/wx.BOTTOM flags, 285
wxDesigner environment, 6
wxGlade environment, 6
wxPython GUI toolkit, 277, 291, 597
creating application object, 280
creating frames (windows), 281
creating widgets (components), 281
event handling, 286
importing wx module, 280
interface elements, 280
minimal requirements for, 279
positions and sizes, 283
titles and labels, 282
using relative coordinates, 284
choosing between GUI toolkits, 278
demo distribution, 279
downloading, 278
example illustrating, 289
GUI client project, 537
installing, 279
wxWindows platform
wxPython GUI toolkit, 277
%X, %x conversion specifiers, 57
XHTML
advantages over HTML, 325
XML, 435
uses of, 436
creating content handler, 439
creating simple content handler, 441
dispatcher mix-in classes, 444, 446
events/event handlers, 439–441, 448–450
factoring out header/footer/default handling, 446
further exploration, 451
goals, 436
handling special characters, 450
installing, PyXML, 437
parsing XML file, 439
SAX parser, 436
Simple API for XML (SAX), 435, 438
support for directories, 447
xml.sax module
parse function, 439
xml.sax.handler module
ContentHandler class, 439
XMLDestination class
news gathering project, 468
XML-RPC
remote procedure calls with, 345
XML-RPC file sharing project, 517–535
avoiding loops, 518
connecting to nodes, 518
creating client interface, 527–528
further exploration, 534
node communication, 518
preparations, 519
requirements, 518
tools, 518
validating file names, 529–534
XML-RPC server
SimpleXMLRPCServer module, 310
XML-RPC file sharing project, 520, 527
XPath, 325
xrange function, 100, 101, 112, 584
changes in Python 3.0, 606
xreadlines method, files
lazy line iteration with, 272
YAML
markup systems and web sites, 424
yield expression, generators, 198, 199
yield statement, generators, 195, 198
yield statements, 590
Zawinski, Jamie, 242
ZeroDivisionError class, 161, 163, 576
catching with more than one except clause, 165
zero-padding, string formatting, 58
zeros
numbers containing leading zeros, 70
zfill method, strings, 588
zip files
sdist command, Distutils, 387
changes in Python 3.0, 605
constructing PolyLine objects, 430
“zlib not available” warning, 429
ZSI, SOAP toolkit, 346