Wesley J. Chun
Praise for the Previous Edition
“The long-awaited second edition of Wesley Chun’s Core Python Programming
proves to be well worth the wait—its deep and broad coverage and useful
exercises will help readers learn and practice good Python.”
—Alex Martelli, author of Python in a Nutshell and editor of Python Cookbook
“There has been lot of good buzz around Wesley Chun’s Core Python
Programming. It turns out that all the buzz is well earned. I think this is the
best book currently available for learning Python. I would recommend Chun’s
book over Learning Python (O’Reilly), Programming Python (O’Reilly), or The
Quick Python Book (Manning).”
—David Mertz, Ph.D., IBM DeveloperWorks
“I have been doing a lot of research [on] Python for the past year and have
seen a number of positive reviews of your book. The sentiment expressed
confirms the opinion that Core Python Programming is now considered the
standard introductory text.”
—Richard Ozaki, Lockheed Martin
“Finally, a book good enough to be both a textbook and a reference on the
Python language now exists.”
—Michael Baxter, Linux Journal
“Very well written. It is the clearest, friendliest book I have come across
yet for explaining Python, and putting it in a wider context. It does not
presume a large amount of other experience. It does go into some important
Python topics carefully and in depth. Unlike too many beginner
books, it never condescends or tortures the reader with childish hide-andseek
prose games. [It] sticks to gaining a solid grasp of Python syntax and structure.”
—http://python.org bookstore Web site
“[If ] I could only own one Python book, it would be Core Python Programming
by Wesley Chun. This book manages to cover more topics in more depth
than Learning Python but includes it all in one book that also more than
adequately covers the core language. [If] you are in the market for just one
book about Python, I recommend this book. You will enjoy reading it,
including its wry programmer’s wit. More importantly, you will learn
Python. Even more importantly, you will find it invaluable in helping
you in your day-to-day Python programming life. Well done, Mr. Chun!”
—Ron Stephens, Python Learning Foundation
“I think the best language for beginners is Python, without a doubt. My
favorite book is Core Python Programming.”
—s003apr, MP3Car.com Forums
“Personally, I really like Python. It’s simple to learn, completely intuitive,
amazingly flexible, and pretty darned fast. Python has only just started to
claim mindshare in the Windows world, but look for it to start gaining lots
of support as people discover it. To learn Python, I’d start with Core Python
Programming by Wesley Chun.”
—Bill Boswell, MCSE, Microsoft Certified Professional Magazine Online
“If you learn well from books, I suggest Core Python Programming. It is by
far the best I’ve found. I’m a Python newbie as well and in three months’
time I’ve been able to implement Python in projects at work (automating
MSOffice, SQL DB stuff, etc.).”
—ptonman, Dev Shed Forums
“Python is simply a beautiful language. It’s easy to learn, it’s cross-platform,
and it works. It has achieved many of the technical goals that Java
strives for. A one-sentence description of Python would be: ‘All other languages
appear to have evolved over time—but Python was designed.’ And
it was designed well. Unfortunately, there aren’t a large number of books for
Python. The best one I’ve run across so far is Core Python Programming.”
—Chris Timmons, C. R. Timmons Consulting
“If you like the Prentice Hall Core series, another good full-blown treatment
to consider would be Core Python Programming. It addresses in elaborate
concrete detail many practical topics that get little, if any, coverage in other books.”
—Mitchell L. Model, MLM Consulting
“The simplified yet deep level of detail, comprehensive coverage of material,
and informative historical references make this book perfect for the classroom...
An easy read, with complex examples presented simply, and great
historical references rarely found in such books. Awesome!”
—Gloria W.
Book Details
Price
|
2.50 USD |
---|---|
Pages
| 886 p |
File Size
|
9,570 KB |
File Type
|
PDF format |
ISBN-13 ISBN-10
| 978-0-13-267820-9 0-13-267820-9 |
Copyright
| 2012 Pearson Education, Inc |
Wesley Chun was initiated into the world of computing during high
school, using BASIC and 6502 assembly on Commodore systems. This was
followed by Pascal on the Apple IIe, and then ForTran on punch cards. It
was the last of these that made him a careful/cautious developer, because
sending the deck out to the school district’s mainframe and getting the
results was a one-week round-trip process. Wesley also converted the
journalism class from typewriters to Osborne 1 CP/M computers. He got
his first paying job as a student-instructor teaching BASIC programming to
fourth, fifth, and sixth graders and their parents.
After high school, Wesley went to University of California at Berkeley
as a California Alumni Scholar. He graduated with an AB in applied math
(computer science) and a minor in music (classical piano). While at Cal, he
coded in Pascal, Logo, and C. He also took a tutoring course that featured
videotape training and psychological counseling. One of his summer
internships involved coding in a 4GL and writing a “Getting Started” user
manual. He then continued his studies several years later at University of
California, Santa Barbara, receiving an MS in computer science (distributed
systems). While there, he also taught C programming. A paper based on his
master’s thesis was nominated for Best Paper at the 29th HICSS conference,
and a later version appeared in the University of Singapore’s Journal of High
Performance Computing.
Wesley has been in the software industry since graduating and has continued
to teach and write, publishing several books and delivering hundreds
of conference talks and tutorials, plus Python courses, both to the
public as well as private corporate training. Wesley’s Python experience
began with version 1.4 at a startup where he designed the Yahoo! Mail
spellchecker and address book. He then became the lead engineer for
Yahoo! People Search. After leaving Yahoo!, he wrote the first edition of
this book and then traveled around the world. Since returning, he has
used Python in a variety of ways, from local product search, anti-spam
and antivirus e-mail appliances, and Facebook games/applications to
something completely different: software for doctors to perform spinal
fracture analysis.
In his spare time, Wesley enjoys piano, bowling, basketball, bicycling,
ultimate frisbee, poker, traveling, and spending time with his family. He
volunteers for Python users groups, the Tutor mailing list, and PyCon.
He also maintains the Alan Parsons Project Monster Discography. If you
think you’re a fan but don’t have “Freudiana,” you had better find it! At
the time of this writing, Wesley was a Developer Advocate at Google, representing
its cloud products. He is based in Silicon Valley, and you can follow
him at @wescpy or plus.ly/wescpy.
PREFACE
Welcome to the Third Edition of Core Python
We are delighted that you have engaged us to help you learn Python as
quickly and as deeply as possible. The goal of the Core Python series of
books is not to just teach developers the Python language; we want you
you to develop enough of a personal knowledge base to be able to develop
software in any application area.
In our other Core Python offerings, Core Python Programming and Core
Python Language Fundamentals, we not only teach you the syntax of the
Python language, but we also strive to give you in-depth knowledge of
how Python works under the hood. We believe that armed with this
knowledge, you will write more effective Python applications, whether
you’re a beginner to the language or a journeyman (or journeywoman!).
Upon completion of either or any other introductory Python books, you
might be satisfied that you have learned Python and learned it well. By
completing many of the exercises, you’re probably even fairly confident in
your newfound Python coding skills. Still, you might be left wondering,
“Now what? What kinds of applications can I build with Python?” Perhaps
you learned Python for a work project that’s constrained to a very
narrow focus. “What else can I build with Python?”
About This Third Edition
At the time the first edition of this book was published, Python was entering
its second era with the release of version 2.0. Since then, the language
has undergone significant improvements that have contributed to the
overall continued success, acceptance, and growth in the use of the language.
Deficiencies have been removed and new features added that bring
a new level of power and sophistication to Python developers worldwide.
The second edition of the book came out in 2006, at the height of Python’s
ascendance, during the time of its most popular release to date, 2.5.
The second edition was released to rave reviews and ended up outselling
the first edition. Python itself had won numerous accolades since that
time as well, including the following:
• Tiobe (www.tiobe.com)
– Language of the Year (2007, 2010)
• LinuxJournal (linuxjournal.com)
– Favorite Programming Language (2009–2011)
– Favorite Scripting Language (2006–2008, 2010, 2011)
• LinuxQuestions.org Members Choice Awards
– Language of the Year (2007–2010)
These awards and honors have helped propel Python even further.
Now it’s on its next generation with Python 3. Likewise, Core Python Programming
is moving towards its “third generation,” too, as I’m exceedingly
pleased that Prentice Hall has asked me to develop this third edition.
Because version 3.x is backward-incompatible with Python 1 and 2, it will
take some time before it is universally adopted and integrated into industry.
We are happy to guide you through this transition. The code in this
edition will be presented in both Python 2 and 3 (as appropriate—not
everything has been ported yet). We’ll also discuss various tools and practices
when porting.
The changes brought about in version 3.x continue the trend of iterating
and improving the language, taking a larger step toward removing some
of its last major flaws, and representing a bigger jump in the continuing
evolution of the language. Similarly, the structure of the book is also making
a rather significant transition. Due to its size and scope, Core Python
Programming as it has existed wouldn’t be able to handle all the new material
introduced in this third edition.
Therefore, Prentice Hall and I have decided the best way of moving forward
is to take that logical division represented by Parts I and II of the previous
editions, representing the core language and advanced applications
topics, respectively, and divide the book into two volumes at this juncture.
You are holding in your hands (perhaps in eBook form) the second half of
the third edition of Core Python Programming. The good news is that the
first half is not required in order to make use of the rich amount of content
in this volume. We only recommend that you have intermediate Python
experience. If you’ve learned Python recently and are fairly comfortable
with using it, or have existing Python skills and want to take it to the next
level, then you’ve come to the right place!
As existing Core Python Programming readers already know, my primary
focus is teaching you the core of the Python language in a comprehensive
manner, much more than just its syntax (which you don’t really need
a book to learn, right?). Knowing more about how Python works under
the hood—including the relationship between data objects and memory
management—will make you a much more effective Python programmer
right out of the gate. This is what Part I, and now Core Python Language
Fundamentals, is all about.
As with all editions of this book, I will continue to update the book’s
Web site and my blog with updates, downloads, and other related articles
to keep this publication as contemporary as possible, regardless to which
new release of Python you have migrated.
For existing readers, the new topics we have added to this edition include:
• Web-based e-mail examples (Chapter 3)
• Using Tile/Ttk (Chapter 5)
• Using MongoDB (Chapter 6)
• More significant Outlook and PowerPoint examples (Chapter 7)
• Web server gateway interface (WSGI) (Chapter 10)
• Using Twitter (Chapter 13)
• Using Google+ (Chapter 15)
In addition, we are proud to introduce three brand new chapters to the
book: Chapter 11, “Web Frameworks: Django,” Chapter 12, “Cloud Computing:
Google App Engine,” and Chapter 14, “Text Processing.” These represent
new or ongoing areas of application development for which Python
is used quite often. All existing chapters have been refreshed and updated
to the latest versions of Python, possibly including new material. Take a
look at the chapter guide that follows for more details on what to expect
from every part of this volume.
Table of Contents
Preface xv
Acknowledgments xxvii
About the Author xxxi
Part I General Application Topics
Chapter 1 Regular Expressions
1.1 Introduction/Motivation 3
1.2 Special Symbols and Characters 6
1.3 Regexes and Python 16
1.4 Some Regex Examples 36
1.5 A Longer Regex Example 41
1.6 Exercises 48
Chapter 2 Network Programming
2.1 Introduction 54
2.2 What Is Client/Server Architecture? 54
2.3 Sockets: Communication Endpoints 58
2.4 Network Programming in Python 61
2.5 *The SocketServer Module 79
2.6 *Introduction to the Twisted Framework 84
2.7 Related Modules 88
2.8 Exercises 89
Chapter 3 Internet Client Programming
3.1 What Are Internet Clients? 95
3.2 Transferring Files 96
3.3 Network News 104
3.4 E-Mail 114
3.5 Related Modules 146
3.6 Exercises 148
Chapter 4 Multithreaded Programming
4.1 Introduction/Motivation 157
4.2 Threads and Processes 158
4.3 Threads and Python 160
4.4 The thread Module 164
4.5 The threading Module 169
4.6 Comparing Single vs. Multithreaded Execution 180
4.7 Multithreading in Practice 182
4.8 Producer-Consumer Problem and the Queue/queue Module 202
4.9 Alternative Considerations to Threads 206
4.10 Related Modules 209
4.11 Exercises 210
Chapter 5 GUI Programming
5.1 Introduction 214
5.2 Tkinter and Python Programming 216
5.3 Tkinter Examples 221
5.4 A Brief Tour of Other GUIs 236
5.5 Related Modules and Other GUIs 247
5.6 Exercises 250
Chapter 6 Database Programming
6.1 Introduction 254
6.2 The Python DB-API 259
6.3 ORMs 289
6.4 Non-Relational Databases 309
6.5 Related References 316
6.6 Exercises 319
Chapter 7 *Programming Microsoft Office
7.1 Introduction 325
7.2 COM Client Programming with Python 326
7.3 Introductory Examples 328
7.4 Intermediate Examples 338
7.5 Related Modules/Packages 357
7.6 Exercises 357
Chapter 8 Extending Python4
8.1 Introduction/Motivation 365
8.2 Extending Python by Writing Extensions 368
8.3 Related Topics 384
8.4 Exercises 388
Part II Web Development
Chapter 9 Web Clients and Servers
9.1 Introduction 391
9.2 Python Web Client Tools 396
9.3 Web Clients 410
9.4 Web (HTTP) Servers 428
9.5 Related Modules 433
9.6 Exercises 436
Chapter 10 Web Programming: CGI and WSGI
10.1 Introduction 442
10.2 Helping Web Servers Process Client Data 442
10.3 Building CGI Applications 446
10.4 Using Unicode with CGI 464
10.5 Advanced CGI 466
10.6 Introduction to WSGI 478
10.7 Real-World Web Development 487
10.8 Related Modules 488
10.9 Exercises 490
Chapter 11 Web Frameworks: Django
11.1 Introduction 494
11.2 Web Frameworks 494
11.3 Introduction to Django 496
11.4 Projects and Apps 501
11.5 Your “Hello World” Application (A Blog) 507
11.6 Creating a Model to Add Database Service 509
11.7 The Python Application Shell 514
11.8 The Django Administration App 518
11.9 Creating the Blog’s User Interface 527
11.10 Improving the Output 537
11.11 Working with User Input 542
11.12 Forms and Model Forms 546
11.13 More About Views 551
11.14 *Look-and-Feel Improvements 553
11.15 *Unit Testing 554
11.16 *An Intermediate Django App: The TweetApprover 564
11.17 Resources 597
11.18 Conclusion 597
11.19 Exercises 598
Chapter 12 Cloud Computing: Google App Engine
12.1 Introduction 605
12.2 What Is Cloud Computing? 605
12.3 The Sandbox and the App Engine SDK 612
12.4 Choosing an App Engine Framework 617
12.5 Python 2.7 Support 626
12.6 Comparisons to Django 628
12.7 Morphing “Hello World” into a Simple Blog 631
12.8 Adding Memcache Service 647
12.9 Static Files 651
12.10 Adding Users Service 652
12.11 Remote API Shell 654
12.12 Lightning Round (with Python Code) 656
12.13 Sending Instant Messages by Using XMPP 660
12.14 Processing Images 662
12.15 Task Queues (Unscheduled Tasks) 663
12.16 Profiling with Appstats 670
12.17 The URLfetch Service 672
12.18 Lightning Round (without Python Code) 673
12.19 Vendor Lock-In 675
12.20 Resources 676
12.21 Conclusion 679
12.22 Exercises 680
Chapter 13 Web Services
13.1 Introduction 685
13.2 The Yahoo! Finance Stock Quote Server 685
13.3 Microblogging with Twitter 690
13.4 Exercises 707
Part III Supplemental/Experimental
Chapter 14 Text Processing
14.1 Comma-Separated Values 715
14.2 JavaScript Object Notation 719
14.3 Extensible Markup Language 724
14.4 References 738
14.5 Related Modules 740
14.6 Exercises 740
Chapter 15 Miscellaneous
15.1 Jython 744
15.2 Google+ 748
15.3 Exercises 759
Appendix A Answers to Selected Exercises
Appendix B Reference Tables
Appendix C Python 3: The Evolution of a Programming Language
C.1 Why Is Python Changing? 799
C.2 What Has Changed? 799
C.3 Migration Tools 805
C.4 Conclusion 806
C.5 References 806
Appendix D Python 3 Migration with 2.6+
D.1 Python 3: The Next Generation 807
D.2 Integers 809
D.3 Built-In Functions 812
D.4 Object-Oriented Programming: Two Different Class Objects 814
D.5 Strings 815
D.6 Exceptions 816
D.7 Other Transition Tools and Tips 817
D.8 Writing Code That is Compatible in Both Versions 2.x and 3.x 818
D.9 Conclusion 822
Index 823
Who Should Read This Book?
This book is meant for anyone who already knows some Python but wants
to know more and expand their application development skillset.
Python is used in many fields, including engineering, information technology,
science, business, entertainment, and so on. This means that the list
of Python users (and readers of this book) includes but is not limited to
• Software engineers
• Hardware design/CAD engineers
• QA/testing and automation framework developers
• IS/IT/system and network administrators
• Scientists and mathematicians
• Technical or project management staff
• Multimedia or audio/visual engineers
• SCM or release engineers
• Web masters and content management staff
• Customer/technical support engineers
• Database engineers and administrators
• Research and development engineers
• Software integration and professional services staff
• Collegiate and secondary educators
• Web service engineers
• Financial software engineers
• And many others!
Some of the most famous companies that use Python include Google,
Yahoo!, NASA, Lucasfilm/Industrial Light and Magic, Red Hat, Zope, Disney,
Pixar, and Dreamworks.