You are previewing Learning Python, 4th Edition.

Learning Python, 4th Edition

Cover of Learning Python, 4th Edition by Mark Lutz Published by O'Reilly Media, Inc.
  1. Learning Python
  2. Dedication
  3. A Note Regarding Supplemental Files
  4. Preface
    1. About This Fourth Edition
      1. Coverage for Both 3.0 and 2.6
      2. New Chapters
      3. Changes to Existing Material
      4. Specific Language Extensions in 2.6 and 3.0
      5. Specific Language Removals in 3.0
    2. About The Third Edition
      1. The Third Edition’s Python Language Changes
      2. The Third Edition’s Python Training Changes
      3. The Third Edition’s Structural Changes
      4. The Third Edition’s Scope Changes
    3. About This Book
      1. This Book’s Prerequisites
      2. This Book’s Scope and Other Books
      3. This Book’s Style and Structure
    4. Book Updates
    5. About the Programs in This Book
    6. Using Code Examples
    7. Font Conventions
    8. Safari® Books Online
    9. How to Contact Us
    10. Acknowledgments
  5. I. Getting Started
    1. 1. A Python Q&A Session
      1. Why Do People Use Python?
      2. Is Python a “Scripting Language”?
      3. OK, but What’s the Downside?
      4. Who Uses Python Today?
      5. What Can I Do with Python?
      6. How Is Python Supported?
      7. What Are Python’s Technical Strengths?
      8. How Does Python Stack Up to Language X?
      9. Chapter Summary
      10. Test Your Knowledge: Quiz
      11. Test Your Knowledge: Answers
    2. 2. How Python Runs Programs
      1. Introducing the Python Interpreter
      2. Program Execution
      3. Execution Model Variations
      4. Chapter Summary
      5. Test Your Knowledge: Quiz
      6. Test Your Knowledge: Answers
    3. 3. How You Run Programs
      1. The Interactive Prompt
      2. System Command Lines and Files
      3. Clicking File Icons
      4. Module Imports and Reloads
      5. Using exec to Run Module Files
      6. The IDLE User Interface
      7. Other IDEs
      8. Other Launch Options
      9. Which Option Should I Use?
      10. Chapter Summary
      11. Test Your Knowledge: Quiz
      12. Test Your Knowledge: Answers
      13. Test Your Knowledge: Part I Exercises
  6. II. Types and Operations
    1. 4. Introducing Python Object Types
      1. Why Use Built-in Types?
      2. Numbers
      3. Strings
      4. Lists
      5. Dictionaries
      6. Tuples
      7. Files
      8. Other Core Types
      9. Chapter Summary
      10. Test Your Knowledge: Quiz
      11. Test Your Knowledge: Answers
    2. 5. Numeric Types
      1. Numeric Type Basics
      2. Numbers in Action
      3. Other Numeric Types
      4. Numeric Extensions
      5. Chapter Summary
      6. Test Your Knowledge: Quiz
      7. Test Your Knowledge: Answers
    3. 6. The Dynamic Typing Interlude
      1. The Case of the Missing Declaration Statements
      2. Shared References
      3. Dynamic Typing Is Everywhere
      4. Chapter Summary
      5. Test Your Knowledge: Quiz
      6. Test Your Knowledge: Answers
    4. 7. Strings
      1. String Literals
      2. Strings in Action
      3. String Methods
      4. String Formatting Expressions
      5. String Formatting Method Calls
      6. General Type Categories
      7. Chapter Summary
      8. Test Your Knowledge: Quiz
      9. Test Your Knowledge: Answers
    5. 8. Lists and Dictionaries
      1. Lists
      2. Lists in Action
      3. Dictionaries
      4. Dictionaries in Action
      5. Chapter Summary
      6. Test Your Knowledge: Quiz
      7. Test Your Knowledge: Answers
    6. 9. Tuples, Files, and Everything Else
      1. Tuples
      2. Files
      3. Type Categories Revisited
      4. Object Flexibility
      5. References Versus Copies
      6. Comparisons, Equality, and Truth
      7. Python’s Type Hierarchies
      8. Other Types in Python
      9. Built-in Type Gotchas
      10. Chapter Summary
      11. Test Your Knowledge: Quiz
      12. Test Your Knowledge: Answers
      13. Test Your Knowledge: Part II Exercises
  7. III. Statements and Syntax
    1. 10. Introducing Python Statements
      1. Python Program Structure Revisited
      2. A Tale of Two ifs
      3. A Quick Example: Interactive Loops
      4. Chapter Summary
      5. Test Your Knowledge: Quiz
      6. Test Your Knowledge: Answers
    2. 11. Assignments, Expressions, and Prints
      1. Assignment Statements
      2. Expression Statements
      3. Print Operations
      4. Chapter Summary
      5. Test Your Knowledge: Quiz
      6. Test Your Knowledge: Answers
    3. 12. if Tests and Syntax Rules
      1. if Statements
      2. Python Syntax Rules
      3. Truth Tests
      4. The if/else Ternary Expression
      5. Chapter Summary
      6. Test Your Knowledge: Quiz
      7. Test Your Knowledge: Answers
    4. 13. while and for Loops
      1. while Loops
      2. break, continue, pass, and the Loop else
      3. for Loops
      4. Loop Coding Techniques
      5. Chapter Summary
      6. Test Your Knowledge: Quiz
      7. Test Your Knowledge: Answers
    5. 14. Iterations and Comprehensions, Part 1
      1. Iterators: A First Look
      2. List Comprehensions: A First Look
      3. Other Iteration Contexts
      4. New Iterables in Python 3.0
      5. Other Iterator Topics
      6. Chapter Summary
      7. Test Your Knowledge: Quiz
      8. Test Your Knowledge: Answers
    6. 15. The Documentation Interlude
      1. Python Documentation Sources
      2. Common Coding Gotchas
      3. Chapter Summary
      4. Test Your Knowledge: Quiz
      5. Test Your Knowledge: Answers
      6. Test Your Knowledge: Part III Exercises
  8. IV. Functions
    1. 16. Function Basics
      1. Why Use Functions?
      2. Coding Functions
      3. A First Example: Definitions and Calls
      4. A Second Example: Intersecting Sequences
      5. Chapter Summary
      6. Test Your Knowledge: Quiz
      7. Test Your Knowledge: Answers
    2. 17. Scopes
      1. Python Scope Basics
      2. The global Statement
      3. Scopes and Nested Functions
      4. The nonlocal Statement
      5. Chapter Summary
      6. Test Your Knowledge: Quiz
      7. Test Your Knowledge: Answers
    3. 18. Arguments
      1. Argument-Passing Basics
      2. Special Argument-Matching Modes
      3. The min Wakeup Call!
      4. Generalized Set Functions
      5. Emulating the Python 3.0 print Function
      6. Chapter Summary
      7. Test Your Knowledge: Quiz
      8. Test Your Knowledge: Answers
    4. 19. Advanced Function Topics
      1. Function Design Concepts
      2. Recursive Functions
      3. Function Objects: Attributes and Annotations
      4. Anonymous Functions: lambda
      5. Mapping Functions over Sequences: map
      6. Functional Programming Tools: filter and reduce
      7. Chapter Summary
      8. Test Your Knowledge: Quiz
      9. Test Your Knowledge: Answers
    5. 20. Iterations and Comprehensions, Part 2
      1. List Comprehensions Revisited: Functional Tools
      2. Iterators Revisited: Generators
      3. 3.0 Comprehension Syntax Summary
      4. Timing Iteration Alternatives
      5. Function Gotchas
      6. Chapter Summary
      7. Test Your Knowledge: Quiz
      8. Test Your Knowledge: Answers
      9. Test Your Knowledge: Part IV Exercises
  9. V. Modules
    1. 21. Modules: The Big Picture
      1. Why Use Modules?
      2. Python Program Architecture
      3. How Imports Work
      4. The Module Search Path
      5. Chapter Summary
      6. Test Your Knowledge: Quiz
      7. Test Your Knowledge: Answers
    2. 22. Module Coding Basics
      1. Module Creation
      2. Module Usage
      3. Module Namespaces
      4. Reloading Modules
      5. Chapter Summary
      6. Test Your Knowledge: Quiz
      7. Test Your Knowledge: Answers
    3. 23. Module Packages
      1. Package Import Basics
      2. Package Import Example
      3. Why Use Package Imports?
      4. Package Relative Imports
      5. Chapter Summary
      6. Test Your Knowledge: Quiz
      7. Test Your Knowledge: Answers
    4. 24. Advanced Module Topics
      1. Data Hiding in Modules
      2. Enabling Future Language Features
      3. Mixed Usage Modes: __name__ and __main__
      4. Changing the Module Search Path
      5. The as Extension for import and from
      6. Modules Are Objects: Metaprograms
      7. Importing Modules by Name String
      8. Transitive Module Reloads
      9. Module Design Concepts
      10. Module Gotchas
      11. Chapter Summary
      12. Test Your Knowledge: Quiz
      13. Test Your Knowledge: Answers
      14. Test Your Knowledge: Part V Exercises
  10. VI. Classes and OOP
    1. 25. OOP: The Big Picture
      1. Why Use Classes?
      2. OOP from 30,000 Feet
      3. Chapter Summary
      4. Test Your Knowledge: Quiz
      5. Test Your Knowledge: Answers
    2. 26. Class Coding Basics
      1. Classes Generate Multiple Instance Objects
      2. Classes Are Customized by Inheritance
      3. Classes Can Intercept Python Operators
      4. The World’s Simplest Python Class
      5. Chapter Summary
      6. Test Your Knowledge: Quiz
      7. Test Your Knowledge: Answers
    3. 27. A More Realistic Example
      1. Step 1: Making Instances
      2. Step 2: Adding Behavior Methods
      3. Step 3: Operator Overloading
      4. Step 4: Customizing Behavior by Subclassing
      5. Step 5: Customizing Constructors, Too
      6. Step 6: Using Introspection Tools
      7. Step 7 (Final): Storing Objects in a Database
      8. Future Directions
      9. Chapter Summary
      10. Test Your Knowledge: Quiz
      11. Test Your Knowledge: Answers
    4. 28. Class Coding Details
      1. The class Statement
      2. Methods
      3. Inheritance
      4. Namespaces: The Whole Story
      5. Documentation Strings Revisited
      6. Classes Versus Modules
      7. Chapter Summary
      8. Test Your Knowledge: Quiz
      9. Test Your Knowledge: Answers
    5. 29. Operator Overloading
      1. The Basics
      2. Indexing and Slicing: __getitem__ and __setitem__
      3. Index Iteration: __getitem__
      4. Iterator Objects: __iter__ and __next__
      5. Membership: __contains__, __iter__, and __getitem__
      6. Attribute Reference: __getattr__ and __setattr__
      7. String Representation: __repr__ and __str__
      8. Right-Side and In-Place Addition: __radd__ and __iadd__
      9. Call Expressions: __call__
      10. Comparisons: __lt__, __gt__, and Others
      11. Boolean Tests: __bool__ and __len__
      12. Object Destruction: __del__
      13. Chapter Summary
      14. Test Your Knowledge: Quiz
      15. Test Your Knowledge: Answers
    6. 30. Designing with Classes
      1. Python and OOP
      2. OOP and Inheritance: “Is-a” Relationships
      3. OOP and Composition: “Has-a” Relationships
      4. OOP and Delegation: “Wrapper” Objects
      5. Pseudoprivate Class Attributes
      6. Methods Are Objects: Bound or Unbound
      7. Multiple Inheritance: “Mix-in” Classes
      8. Classes Are Objects: Generic Object Factories
      9. Other Design-Related Topics
      10. Chapter Summary
      11. Test Your Knowledge: Quiz
      12. Test Your Knowledge: Answers
    7. 31. Advanced Class Topics
      1. Extending Built-in Types
      2. The “New-Style” Class Model
      3. New-Style Class Changes
      4. New-Style Class Extensions
      5. Static and Class Methods
      6. Decorators and Metaclasses: Part 1
      7. Class Gotchas
      8. Chapter Summary
      9. Test Your Knowledge: Quiz
      10. Test Your Knowledge: Answers
      11. Test Your Knowledge: Part VI Exercises
  11. VII. Exceptions and Tools
    1. 32. Exception Basics
      1. Why Use Exceptions?
      2. Exceptions: The Short Story
      3. Chapter Summary
      4. Test Your Knowledge: Quiz
      5. Test Your Knowledge: Answers
    2. 33. Exception Coding Details
      1. The try/except/else Statement
      2. The try/finally Statement
      3. Unified try/except/finally
      4. The raise Statement
      5. The assert Statement
      6. with/as Context Managers
      7. Chapter Summary
      8. Test Your Knowledge: Quiz
      9. Test Your Knowledge: Answers
    3. 34. Exception Objects
      1. Exceptions: Back to the Future
      2. Why Exception Hierarchies?
      3. Built-in Exception Classes
      4. Custom Print Displays
      5. Custom Data and Behavior
      6. Chapter Summary
      7. Test Your Knowledge: Quiz
      8. Test Your Knowledge: Answers
    4. 35. Designing with Exceptions
      1. Nesting Exception Handlers
      2. Exception Idioms
      3. Exception Design Tips and Gotchas
      4. Core Language Summary
      5. Chapter Summary
      6. Test Your Knowledge: Quiz
      7. Test Your Knowledge: Answers
      8. Test Your Knowledge: Part VII Exercises
  12. VIII. Advanced Topics
    1. 36. Unicode and Byte Strings
      1. String Changes in 3.0
      2. String Basics
      3. Python 3.0 Strings in Action
      4. Coding Unicode Strings
      5. Using 3.0 Bytes Objects
      6. Using 3.0 (and 2.6) bytearray Objects
      7. Using Text and Binary Files
      8. Using Unicode Files
      9. Other String Tool Changes in 3.0
      10. Chapter Summary
      11. Test Your Knowledge: Quiz
      12. Test Your Knowledge: Answers
    2. 37. Managed Attributes
      1. Why Manage Attributes?
      2. Properties
      3. Descriptors
      4. __getattr__ and __getattribute__
      5. Example: Attribute Validations
      6. Chapter Summary
      7. Test Your Knowledge: Quiz
    3. 38. Decorators
      1. What’s a Decorator?
      2. The Basics
      3. Coding Function Decorators
      4. Coding Class Decorators
      5. Managing Functions and Classes Directly
      6. Example: “Private” and “Public” Attributes
      7. Example: Validating Function Arguments
      8. Chapter Summary
      9. Test Your Knowledge: Quiz
      10. Test Your Knowledge: Answers
    4. 39. Metaclasses
      1. To Metaclass or Not to Metaclass
      2. The Metaclass Model
      3. Declaring Metaclasses
      4. Coding Metaclasses
      5. Example: Adding Methods to Classes
      6. Example: Applying Decorators to Methods
      7. Chapter Summary
      8. Test Your Knowledge: Quiz
      9. Test Your Knowledge: Answers
  13. IX. Appendixes
    1. A. Installation and Configuration
      1. Installing the Python Interpreter
      2. Configuring Python
      3. For More Help
    2. B. Solutions to End-of-Part Exercises
      1. Part I, Getting Started
      2. Part II, Types and Operations
      3. Part III, Statements and Syntax
      4. Part IV, Functions
      5. Part V, Modules
      6. Part VI, Classes and OOP
      7. Part VII, Exceptions and Tools
  14. Index
  15. About the Author
  16. Colophon
  17. Copyright
O'Reilly logo

Chapter 1. A Python Q&A Session

If you’ve bought this book, you may already know what Python is and why it’s an important tool to learn. If you don’t, you probably won’t be sold on Python until you’ve learned the language by reading the rest of this book and have done a project or two. But before we jump into details, the first few pages of this book will briefly introduce some of the main reasons behind Python’s popularity. To begin sculpting a definition of Python, this chapter takes the form of a question-and-answer session, which poses some of the most common questions asked by beginners.

Why Do People Use Python?

Because there are many programming languages available today, this is the usual first question of newcomers. Given that there are roughly 1 million Python users out there at the moment, there really is no way to answer this question with complete accuracy; the choice of development tools is sometimes based on unique constraints or personal preference.

But after teaching Python to roughly 225 groups and over 3,000 students during the last 12 years, some common themes have emerged. The primary factors cited by Python users seem to be these:

Software quality

For many, Python’s focus on readability, coherence, and software quality in general sets it apart from other tools in the scripting world. Python code is designed to be readable, and hence reusable and maintainable—much more so than traditional scripting languages. The uniformity of Python code makes it easy to understand, even if you did not write it. In addition, Python has deep support for more advanced software reuse mechanisms, such as object-oriented programming (OOP).

Developer productivity

Python boosts developer productivity many times beyond compiled or statically typed languages such as C, C++, and Java. Python code is typically one-third to one-fifth the size of equivalent C++ or Java code. That means there is less to type, less to debug, and less to maintain after the fact. Python programs also run immediately, without the lengthy compile and link steps required by some other tools, further boosting programmer speed.

Program portability

Most Python programs run unchanged on all major computer platforms. Porting Python code between Linux and Windows, for example, is usually just a matter of copying a script’s code between machines. Moreover, Python offers multiple options for coding portable graphical user interfaces, database access programs, web-based systems, and more. Even operating system interfaces, including program launches and directory processing, are as portable in Python as they can possibly be.

Support libraries

Python comes with a large collection of prebuilt and portable functionality, known as the standard library. This library supports an array of application-level programming tasks, from text pattern matching to network scripting. In addition, Python can be extended with both homegrown libraries and a vast collection of third-party application support software. Python’s third-party domain offers tools for website construction, numeric programming, serial port access, game development, and much more. The NumPy extension, for instance, has been described as a free and more powerful equivalent to the Matlab numeric programming system.

Component integration

Python scripts can easily communicate with other parts of an application, using a variety of integration mechanisms. Such integrations allow Python to be used as a product customization and extension tool. Today, Python code can invoke C and C++ libraries, can be called from C and C++ programs, can integrate with Java and .NET components, can communicate over frameworks such as COM, can interface with devices over serial ports, and can interact over networks with interfaces like SOAP, XML-RPC, and CORBA. It is not a standalone tool.

Enjoyment

Because of Python’s ease of use and built-in toolset, it can make the act of programming more pleasure than chore. Although this may be an intangible benefit, its effect on productivity is an important asset.

Of these factors, the first two (quality and productivity) are probably the most compelling benefits to most Python users.

Software Quality

By design, Python implements a deliberately simple and readable syntax and a highly coherent programming model. As a slogan at a recent Python conference attests, the net result is that Python seems to “fit your brain”—that is, features of the language interact in consistent and limited ways and follow naturally from a small set of core concepts. This makes the language easier to learn, understand, and remember. In practice, Python programmers do not need to constantly refer to manuals when reading or writing code; it’s a consistently designed system that many find yields surprisingly regular-looking code.

By philosophy, Python adopts a somewhat minimalist approach. This means that although there are usually multiple ways to accomplish a coding task, there is usually just one obvious way, a few less obvious alternatives, and a small set of coherent interactions everywhere in the language. Moreover, Python doesn’t make arbitrary decisions for you; when interactions are ambiguous, explicit intervention is preferred over “magic.” In the Python way of thinking, explicit is better than implicit, and simple is better than complex.[2]

Beyond such design themes, Python includes tools such as modules and OOP that naturally promote code reusability. And because Python is focused on quality, so too, naturally, are Python programmers.

Developer Productivity

During the great Internet boom of the mid-to-late 1990s, it was difficult to find enough programmers to implement software projects; developers were asked to implement systems as fast as the Internet evolved. Today, in an era of layoffs and economic recession, the picture has shifted. Programming staffs are often now asked to accomplish the same tasks with even fewer people.

In both of these scenarios, Python has shined as a tool that allows programmers to get more done with less effort. It is deliberately optimized for speed of development—its simple syntax, dynamic typing, lack of compile steps, and built-in toolset allow programmers to develop programs in a fraction of the time needed when using some other tools. The net effect is that Python typically boosts developer productivity many times beyond the levels supported by traditional languages. That’s good news in both boom and bust times, and everywhere the software industry goes in between.

Is Python a “Scripting Language”?

Python is a general-purpose programming language that is often applied in scripting roles. It is commonly defined as an object-oriented scripting language—a definition that blends support for OOP with an overall orientation toward scripting roles. In fact, people often use the word “script” instead of “program” to describe a Python code file. In this book, the terms “script” and “program” are used interchangeably, with a slight preference for “script” to describe a simpler top-level file and “program” to refer to a more sophisticated multifile application.

Because the term “scripting language” has so many different meanings to different observers, some would prefer that it not be applied to Python at all. In fact, people tend to make three very different associations, some of which are more useful than others, when they hear Python labeled as such:

Shell tools

Sometimes when people hear Python described as a scripting language, they think it means that Python is a tool for coding operating-system-oriented scripts. Such programs are often launched from console command lines and perform tasks such as processing text files and launching other programs.

Python programs can and do serve such roles, but this is just one of dozens of common Python application domains. It is not just a better shell-script language.

Control language

To others, scripting refers to a “glue” layer used to control and direct (i.e., script) other application components. Python programs are indeed often deployed in the context of larger applications. For instance, to test hardware devices, Python programs may call out to components that give low-level access to a device. Similarly, programs may run bits of Python code at strategic points to support end-user product customization without the need to ship and recompile the entire system’s source code.

Python’s simplicity makes it a naturally flexible control tool. Technically, though, this is also just a common Python role; many (perhaps most) Python programmers code standalone scripts without ever using or knowing about any integrated components. It is not just a control language.

Ease of use

Probably the best way to think of the term “scripting language” is that it refers to a simple language used for quickly coding tasks. This is especially true when the term is applied to Python, which allows much faster program development than compiled languages like C++. Its rapid development cycle fosters an exploratory, incremental mode of programming that has to be experienced to be appreciated.

Don’t be fooled, though—Python is not just for simple tasks. Rather, it makes tasks simple by its ease of use and flexibility. Python has a simple feature set, but it allows programs to scale up in sophistication as needed. Because of that, it is commonly used for quick tactical tasks and longer-term strategic development.

So, is Python a scripting language or not? It depends on whom you ask. In general, the term “scripting” is probably best used to describe the rapid and flexible mode of development that Python supports, rather than a particular application domain.

OK, but What’s the Downside?

After using it for 17 years and teaching it for 12, the only downside to Python I’ve found is that, as currently implemented, its execution speed may not always be as fast as that of compiled languages such as C and C++.

We’ll talk about implementation concepts in detail later in this book. In short, the standard implementations of Python today compile (i.e., translate) source code statements to an intermediate format known as byte code and then interpret the byte code. Byte code provides portability, as it is a platform-independent format. However, because Python is not compiled all the way down to binary machine code (e.g., instructions for an Intel chip), some programs will run more slowly in Python than in a fully compiled language like C.

Whether you will ever care about the execution speed difference depends on what kinds of programs you write. Python has been optimized numerous times, and Python code runs fast enough by itself in most application domains. Furthermore, whenever you do something “real” in a Python script, like processing a file or constructing a graphical user interface (GUI), your program will actually run at C speed, since such tasks are immediately dispatched to compiled C code inside the Python interpreter. More fundamentally, Python’s speed-of-development gain is often far more important than any speed-of-execution loss, especially given modern computer speeds.

Even at today’s CPU speeds, though, there still are some domains that do require optimal execution speeds. Numeric programming and animation, for example, often need at least their core number-crunching components to run at C speed (or better). If you work in such a domain, you can still use Python—simply split off the parts of the application that require optimal speed into compiled extensions, and link those into your system for use in Python scripts.

We won’t talk about extensions much in this text, but this is really just an instance of the Python-as-control-language role we discussed earlier. A prime example of this dual language strategy is the NumPy numeric programming extension for Python; by combining compiled and optimized numeric extension libraries with the Python language, NumPy turns Python into a numeric programming tool that is efficient and easy to use. You may never need to code such extensions in your own Python work, but they provide a powerful optimization mechanism if you ever do.

Who Uses Python Today?

At this writing, the best estimate anyone can seem to make of the size of the Python user base is that there are roughly 1 million Python users around the world today (plus or minus a few). This estimate is based on various statistics, like download rates and developer surveys. Because Python is open source, a more exact count is difficult—there are no license registrations to tally. Moreover, Python is automatically included with Linux distributions, Macintosh computers, and some products and hardware, further clouding the user-base picture.

In general, though, Python enjoys a large user base and a very active developer community. Because Python has been around for some 19 years and has been widely used, it is also very stable and robust. Besides being employed by individual users, Python is also being applied in real revenue-generating products by real companies. For instance:

  • Google makes extensive use of Python in its web search systems, and employs Python’s creator.

  • The YouTube video sharing service is largely written in Python.

  • The popular BitTorrent peer-to-peer file sharing system is a Python program.

  • Google’s popular App Engine web development framework uses Python as its application language.

  • EVE Online, a Massively Multiplayer Online Game (MMOG), makes extensive use of Python.

  • Maya, a powerful integrated 3D modeling and animation system, provides a Python scripting API.

  • Intel, Cisco, Hewlett-Packard, Seagate, Qualcomm, and IBM use Python for hardware testing.

  • Industrial Light & Magic, Pixar, and others use Python in the production of animated movies.

  • JPMorgan Chase, UBS, Getco, and Citadel apply Python for financial market forecasting.

  • NASA, Los Alamos, Fermilab, JPL, and others use Python for scientific programming tasks.

  • iRobot uses Python to develop commercial robotic devices.

  • ESRI uses Python as an end-user customization tool for its popular GIS mapping products.

  • The NSA uses Python for cryptography and intelligence analysis.

  • The IronPort email server product uses more than 1 million lines of Python code to do its job.

  • The One Laptop Per Child (OLPC) project builds its user interface and activity model in Python.

And so on. Probably the only common thread amongst the companies using Python today is that Python is used all over the map, in terms of application domains. Its general-purpose nature makes it applicable to almost all fields, not just one. In fact, it’s safe to say that virtually every substantial organization writing software is using Python, whether for short-term tactical tasks, such as testing and administration, or for long-term strategic product development. Python has proven to work well in both modes.

For more details on companies using Python today, see Python’s website at http://www.python.org.

What Can I Do with Python?

In addition to being a well-designed programming language, Python is useful for accomplishing real-world tasks—the sorts of things developers do day in and day out. It’s commonly used in a variety of domains, as a tool for scripting other components and implementing standalone programs. In fact, as a general-purpose language, Python’s roles are virtually unlimited: you can use it for everything from website development and gaming to robotics and spacecraft control.

However, the most common Python roles currently seem to fall into a few broad categories. The next few sections describe some of Python’s most common applications today, as well as tools used in each domain. We won’t be able to explore the tools mentioned here in any depth—if you are interested in any of these topics, see the Python website or other resources for more details.

Systems Programming

Python’s built-in interfaces to operating-system services make it ideal for writing portable, maintainable system-administration tools and utilities (sometimes called shell tools). Python programs can search files and directory trees, launch other programs, do parallel processing with processes and threads, and so on.

Python’s standard library comes with POSIX bindings and support for all the usual OS tools: environment variables, files, sockets, pipes, processes, multiple threads, regular expression pattern matching, command-line arguments, standard stream interfaces, shell-command launchers, filename expansion, and more. In addition, the bulk of Python’s system interfaces are designed to be portable; for example, a script that copies directory trees typically runs unchanged on all major Python platforms. The Stackless Python system, used by EVE Online, also offers advanced solutions to multiprocessing requirements.

GUIs

Python’s simplicity and rapid turnaround also make it a good match for graphical user interface programming. Python comes with a standard object-oriented interface to the Tk GUI API called tkinter (Tkinter in 2.6) that allows Python programs to implement portable GUIs with a native look and feel. Python/tkinter GUIs run unchanged on Microsoft Windows, X Windows (on Unix and Linux), and the Mac OS (both Classic and OS X). A free extension package, PMW, adds advanced widgets to the tkinter toolkit. In addition, the wxPython GUI API, based on a C++ library, offers an alternative toolkit for constructing portable GUIs in Python.

Higher-level toolkits such as PythonCard and Dabo are built on top of base APIs such as wxPython and tkinter. With the proper library, you can also use GUI support in other toolkits in Python, such as Qt with PyQt, GTK with PyGTK, MFC with PyWin32, .NET with IronPython, and Swing with Jython (the Java version of Python, described in Chapter 2) or JPype. For applications that run in web browsers or have simple interface requirements, both Jython and Python web frameworks and server-side CGI scripts, described in the next section, provide additional user interface options.

Internet Scripting

Python comes with standard Internet modules that allow Python programs to perform a wide variety of networking tasks, in client and server modes. Scripts can communicate over sockets; extract form information sent to server-side CGI scripts; transfer files by FTP; parse, generate, and analyze XML files; send, receive, compose, and parse email; fetch web pages by URLs; parse the HTML and XML of fetched web pages; communicate over XML-RPC, SOAP, and Telnet; and more. Python’s libraries make these tasks remarkably simple.

In addition, a large collection of third-party tools are available on the Web for doing Internet programming in Python. For instance, the HTMLGen system generates HTML files from Python class-based descriptions, the mod_python package runs Python efficiently within the Apache web server and supports server-side templating with its Python Server Pages, and the Jython system provides for seamless Python/Java integration and supports coding of server-side applets that run on clients.

In addition, full-blown web development framework packages for Python, such as Django, TurboGears, web2py, Pylons, Zope, and WebWare, support quick construction of full-featured and production-quality websites with Python. Many of these include features such as object-relational mappers, a Model/View/Controller architecture, server-side scripting and templating, and AJAX support, to provide complete and enterprise-level web development solutions.

Component Integration

We discussed the component integration role earlier when describing Python as a control language. Python’s ability to be extended by and embedded in C and C++ systems makes it useful as a flexible glue language for scripting the behavior of other systems and components. For instance, integrating a C library into Python enables Python to test and launch the library’s components, and embedding Python in a product enables onsite customizations to be coded without having to recompile the entire product (or ship its source code at all).

Tools such as the SWIG and SIP code generators can automate much of the work needed to link compiled components into Python for use in scripts, and the Cython system allows coders to mix Python and C-like code. Larger frameworks, such as Python’s COM support on Windows, the Jython Java-based implementation, the IronPython .NET-based implementation, and various CORBA toolkits for Python, provide alternative ways to script components. On Windows, for example, Python scripts can use frameworks to script Word and Excel.

Database Programming

For traditional database demands, there are Python interfaces to all commonly used relational database systems—Sybase, Oracle, Informix, ODBC, MySQL, PostgreSQL, SQLite, and more. The Python world has also defined a portable database API for accessing SQL database systems from Python scripts, which looks the same on a variety of underlying database systems. For instance, because the vendor interfaces implement the portable API, a script written to work with the free MySQL system will work largely unchanged on other systems (such as Oracle); all you have to do is replace the underlying vendor interface.

Python’s standard pickle module provides a simple object persistence system—it allows programs to easily save and restore entire Python objects to files and file-like objects. On the Web, you’ll also find a third-party open source system named ZODB that provides a complete object-oriented database system for Python scripts, and others (such as SQLObject and SQLAlchemy) that map relational tables onto Python’s class model. Furthermore, as of Python 2.5, the in-process SQLite embedded SQL database engine is a standard part of Python itself.

Rapid Prototyping

To Python programs, components written in Python and C look the same. Because of this, it’s possible to prototype systems in Python initially, and then move selected components to a compiled language such as C or C++ for delivery. Unlike some prototyping tools, Python doesn’t require a complete rewrite once the prototype has solidified. Parts of the system that don’t require the efficiency of a language such as C++ can remain coded in Python for ease of maintenance and use.

Numeric and Scientific Programming

The NumPy numeric programming extension for Python mentioned earlier includes such advanced tools as an array object, interfaces to standard mathematical libraries, and much more. By integrating Python with numeric routines coded in a compiled language for speed, NumPy turns Python into a sophisticated yet easy-to-use numeric programming tool that can often replace existing code written in traditional compiled languages such as FORTRAN or C++. Additional numeric tools for Python support animation, 3D visualization, parallel processing, and so on. The popular SciPy and ScientificPython extensions, for example, provide additional libraries of scientific programming tools and use NumPy code.

Gaming, Images, Serial Ports, XML, Robots, and More

Python is commonly applied in more domains than can be mentioned here. For example, you can do:

  • Game programming and multimedia in Python with the pygame system

  • Serial port communication on Windows, Linux, and more with the PySerial extension

  • Image processing with PIL, PyOpenGL, Blender, Maya, and others

  • Robot control programming with the PyRo toolkit

  • XML parsing with the xml library package, the xmlrpclib module, and third-party extensions

  • Artificial intelligence programming with neural network simulators and expert system shells

  • Natural language analysis with the NLTK package

You can even play solitaire with the PySol program. You’ll find support for many such fields at the PyPI websites, and via web searches (search Google or http://www.python.org for links).

Many of these specific domains are largely just instances of Python’s component integration role in action again. Adding it as a frontend to libraries of components written in a compiled language such as C makes Python useful for scripting in a wide variety of domains. As a general-purpose language that supports integration, Python is widely applicable.

How Is Python Supported?

As a popular open source system, Python enjoys a large and active development community that responds to issues and develops enhancements with a speed that many commercial software developers would find remarkable (if not downright shocking). Python developers coordinate work online with a source-control system. Changes follow a formal PEP (Python Enhancement Proposal) protocol and must be accompanied by extensions to Python’s extensive regression testing system. In fact, modifying Python today is roughly as involved as changing commercial software—a far cry from Python’s early days, when an email to its creator would suffice, but a good thing given its current large user base.

The PSF (Python Software Foundation), a formal nonprofit group, organizes conferences and deals with intellectual property issues. Numerous Python conferences are held around the world; O’Reilly’s OSCON and the PSF’s PyCon are the largest. The former of these addresses multiple open source projects, and the latter is a Python-only event that has experienced strong growth in recent years. Attendance at PyCon 2008 nearly doubled from the prior year, growing from 586 attendees in 2007 to over 1,000 in 2008. This was on the heels of a 40% attendance increase in 2007, from 410 in 2006. PyCon 2009 had 943 attendees, a slight decrease from 2008, but a still very strong showing during a global recession.

What Are Python’s Technical Strengths?

Naturally, this is a developer’s question. If you don’t already have a programming background, the language in the next few sections may be a bit baffling—don’t worry, we’ll explore all of these terms in more detail as we proceed through this book. For developers, though, here is a quick introduction to some of Python’s top technical features.

It’s Object-Oriented

Python is an object-oriented language, from the ground up. Its class model supports advanced notions such as polymorphism, operator overloading, and multiple inheritance; yet, in the context of Python’s simple syntax and typing, OOP is remarkably easy to apply. In fact, if you don’t understand these terms, you’ll find they are much easier to learn with Python than with just about any other OOP language available.

Besides serving as a powerful code structuring and reuse device, Python’s OOP nature makes it ideal as a scripting tool for object-oriented systems languages such as C++ and Java. For example, with the appropriate glue code, Python programs can subclass (specialize) classes implemented in C++, Java, and C#.

Of equal significance, OOP is an option in Python; you can go far without having to become an object guru all at once. Much like C++, Python supports both procedural and object-oriented programming modes. Its object-oriented tools can be applied if and when constraints allow. This is especially useful in tactical development modes, which preclude design phases.

It’s Free

Python is completely free to use and distribute. As with other open source software, such as Tcl, Perl, Linux, and Apache, you can fetch the entire Python system’s source code for free on the Internet. There are no restrictions on copying it, embedding it in your systems, or shipping it with your products. In fact, you can even sell Python’s source code, if you are so inclined.

But don’t get the wrong idea: “free” doesn’t mean “unsupported.” On the contrary, the Python online community responds to user queries with a speed that most commercial software help desks would do well to try to emulate. Moreover, because Python comes with complete source code, it empowers developers, leading to the creation of a large team of implementation experts. Although studying or changing a programming language’s implementation isn’t everyone’s idea of fun, it’s comforting to know that you can do so if you need to. You’re not dependent on the whims of a commercial vendor; the ultimate documentation source is at your disposal.

As mentioned earlier, Python development is performed by a community that largely coordinates its efforts over the Internet. It consists of Python’s creator—Guido van Rossum, the officially anointed Benevolent Dictator for Life (BDFL) of Python—plus a supporting cast of thousands. Language changes must follow a formal enhancement procedure and be scrutinized by both other developers and the BDFL. Happily, this tends to make Python more conservative with changes than some other languages.

It’s Portable

The standard implementation of Python is written in portable ANSI C, and it compiles and runs on virtually every major platform currently in use. For example, Python programs run today on everything from PDAs to supercomputers. As a partial list, Python is available on:

  • Linux and Unix systems

  • Microsoft Windows and DOS (all modern flavors)

  • Mac OS (both OS X and Classic)

  • BeOS, OS/2, VMS, and QNX

  • Real-time systems such as VxWorks

  • Cray supercomputers and IBM mainframes

  • PDAs running Palm OS, PocketPC, and Linux

  • Cell phones running Symbian OS and Windows Mobile

  • Gaming consoles and iPods

  • And more

Like the language interpreter itself, the standard library modules that ship with Python are implemented to be as portable across platform boundaries as possible. Further, Python programs are automatically compiled to portable byte code, which runs the same on any platform with a compatible version of Python installed (more on this in the next chapter).

What that means is that Python programs using the core language and standard libraries run the same on Linux, Windows, and most other systems with a Python interpreter. Most Python ports also contain platform-specific extensions (e.g., COM support on Windows), but the core Python language and libraries work the same everywhere. As mentioned earlier, Python also includes an interface to the Tk GUI toolkit called tkinter (Tkinter in 2.6), which allows Python programs to implement full-featured graphical user interfaces that run on all major GUI platforms without program changes.

It’s Powerful

From a features perspective, Python is something of a hybrid. Its toolset places it between traditional scripting languages (such as Tcl, Scheme, and Perl) and systems development languages (such as C, C++, and Java). Python provides all the simplicity and ease of use of a scripting language, along with more advanced software-engineering tools typically found in compiled languages. Unlike some scripting languages, this combination makes Python useful for large-scale development projects. As a preview, here are some of the main things you’ll find in Python’s toolbox:

Dynamic typing

Python keeps track of the kinds of objects your program uses when it runs; it doesn’t require complicated type and size declarations in your code. In fact, as you’ll see in Chapter 6, there is no such thing as a type or variable declaration anywhere in Python. Because Python code does not constrain data types, it is also usually automatically applicable to a whole range of objects.

Automatic memory management

Python automatically allocates objects and reclaims (“garbage collects”) them when they are no longer used, and most can grow and shrink on demand. As you’ll learn, Python keeps track of low-level memory details so you don’t have to.

Programming-in-the-large support

For building larger systems, Python includes tools such as modules, classes, and exceptions. These tools allow you to organize systems into components, use OOP to reuse and customize code, and handle events and errors gracefully.

Built-in object types

Python provides commonly used data structures such as lists, dictionaries, and strings as intrinsic parts of the language; as you’ll see, they’re both flexible and easy to use. For instance, built-in objects can grow and shrink on demand, can be arbitrarily nested to represent complex information, and more.

Built-in tools

To process all those object types, Python comes with powerful and standard operations, including concatenation (joining collections), slicing (extracting sections), sorting, mapping, and more.

Library utilities

For more specific tasks, Python also comes with a large collection of precoded library tools that support everything from regular expression matching to networking. Once you learn the language itself, Python’s library tools are where much of the application-level action occurs.

Third-party utilities

Because Python is open source, developers are encouraged to contribute precoded tools that support tasks beyond those supported by its built-ins; on the Web, you’ll find free support for COM, imaging, CORBA ORBs, XML, database access, and much more.

Despite the array of tools in Python, it retains a remarkably simple syntax and design. The result is a powerful programming tool with all the usability of a scripting language.

It’s Mixable

Python programs can easily be “glued” to components written in other languages in a variety of ways. For example, Python’s C API lets C programs call and be called by Python programs flexibly. That means you can add functionality to the Python system as needed, and use Python programs within other environments or systems.

Mixing Python with libraries coded in languages such as C or C++, for instance, makes it an easy-to-use frontend language and customization tool. As mentioned earlier, this also makes Python good at rapid prototyping; systems may be implemented in Python first, to leverage its speed of development, and later moved to C for delivery, one piece at a time, according to performance demands.

It’s Easy to Use

To run a Python program, you simply type it and run it. There are no intermediate compile and link steps, like there are for languages such as C or C++. Python executes programs immediately, which makes for an interactive programming experience and rapid turnaround after program changes—in many cases, you can witness the effect of a program change as fast as you can type it.

Of course, development cycle turnaround is only one aspect of Python’s ease of use. It also provides a deliberately simple syntax and powerful built-in tools. In fact, some have gone so far as to call Python “executable pseudocode.” Because it eliminates much of the complexity in other tools, Python programs are simpler, smaller, and more flexible than equivalent programs in languages like C, C++, and Java.

It’s Easy to Learn

This brings us to a key point of this book: compared to other programming languages, the core Python language is remarkably easy to learn. In fact, you can expect to be coding significant Python programs in a matter of days (or perhaps in just hours, if you’re already an experienced programmer). That’s good news for professional developers seeking to learn the language to use on the job, as well as for end users of systems that expose a Python layer for customization or control.

Today, many systems rely on the fact that end users can quickly learn enough Python to tailor their Python customizations’ code onsite, with little or no support. Although Python does have advanced programming tools, its core language will still seem simple to beginners and gurus alike.

It’s Named After Monty Python

OK, this isn’t quite a technical strength, but it does seem to be a surprisingly well-kept secret that I wish to expose up front. Despite all the reptile icons in the Python world, the truth is that Python creator Guido van Rossum named it after the BBC comedy series Monty Python’s Flying Circus. He is a big fan of Monty Python, as are many software developers (indeed, there seems to almost be a symmetry between the two fields).

This legacy inevitably adds a humorous quality to Python code examples. For instance, the traditional “foo” and “bar” for generic variable names become “spam” and “eggs” in the Python world. The occasional “Brian,” “ni,” and “shrubbery” likewise owe their appearances to this namesake. It even impacts the Python community at large: talks at Python conferences are regularly billed as “The Spanish Inquisition.”

All of this is, of course, very funny if you are familiar with the show, but less so otherwise. You don’t need to be familiar with the series to make sense of examples that borrow references to Monty Python (including many you will see in this book), but at least you now know their root.

How Does Python Stack Up to Language X?

Finally, to place it in the context of what you may already know, people sometimes compare Python to languages such as Perl, Tcl, and Java. We talked about performance earlier, so here we’ll focus on functionality. While other languages are also useful tools to know and use, many people find that Python:

  • Is more powerful than Tcl. Python’s support for “programming in the large” makes it applicable to the development of larger systems.

  • Has a cleaner syntax and simpler design than Perl, which makes it more readable and maintainable and helps reduce program bugs.

  • Is simpler and easier to use than Java. Python is a scripting language, but Java inherits much of the complexity and syntax of systems languages such as C++.

  • Is simpler and easier to use than C++, but it doesn’t often compete with C++; as a scripting language, Python typically serves different roles.

  • Is both more powerful and more cross-platform than Visual Basic. Its open source nature also means it is not controlled by a single company.

  • Is more readable and general-purpose than PHP. Python is sometimes used to construct websites, but it’s also widely used in nearly every other computer domain, from robotics to movie animation.

  • Is more mature and has a more readable syntax than Ruby. Unlike Ruby and Java, OOP is an option in Python—Python does not impose OOP on users or projects to which it may not apply.

  • Has the dynamic flavor of languages like SmallTalk and Lisp, but also has a simple, traditional syntax accessible to developers as well as end users of customizable systems.

Especially for programs that do more than scan text files, and that might have to be read in the future by others (or by you!), many people find that Python fits the bill better than any other scripting or programming language available today. Furthermore, unless your application requires peak performance, Python is often a viable alternative to systems development languages such as C, C++, and Java: Python code will be much less difficult to write, debug, and maintain.

Of course, your author has been a card-carrying Python evangelist since 1992, so take these comments as you may. They do, however, reflect the common experience of many developers who have taken time to explore what Python has to offer.

Chapter Summary

And that concludes the hype portion of this book. In this chapter, we’ve explored some of the reasons that people pick Python for their programming tasks. We’ve also seen how it is applied and looked at a representative sample of who is using it today. My goal is to teach Python, though, not to sell it. The best way to judge a language is to see it in action, so the rest of this book focuses entirely on the language details we’ve glossed over here.

The next two chapters begin our technical introduction to the language. In them, we’ll explore ways to run Python programs, peek at Python’s byte code execution model, and introduce the basics of module files for saving code. The goal will be to give you just enough information to run the examples and exercises in the rest of the book. You won’t really start programming per se until Chapter 4, but make sure you have a handle on the startup details before moving on.

Test Your Knowledge: Quiz

In this edition of the book, we will be closing each chapter with a quick pop quiz about the material presented therein to help you review the key concepts. The answers for these quizzes appear immediately after the questions, and you are encouraged to read the answers once you’ve taken a crack at the questions yourself. In addition to these end-of-chapter quizzes, you’ll find lab exercises at the end of each part of the book, designed to help you start coding Python on your own. For now, here’s your first test. Good luck!

  1. What are the six main reasons that people choose to use Python?

  2. Name four notable companies or organizations using Python today.

  3. Why might you not want to use Python in an application?

  4. What can you do with Python?

  5. What’s the significance of the Python import this statement?

  6. Why does “spam” show up in so many Python examples in books and on the Web?

  7. What is your favorite color?

Test Your Knowledge: Answers

How did you do? Here are the answers I came up with, though there may be multiple solutions to some quiz questions. Again, even if you’re sure you got a question right, I encourage you to look at these answers for additional context. See the chapter’s text for more details if any of these responses don’t make sense to you.

  1. Software quality, developer productivity, program portability, support libraries, component integration, and simple enjoyment. Of these, the quality and productivity themes seem to be the main reasons that people choose to use Python.

  2. Google, Industrial Light & Magic, EVE Online, Jet Propulsion Labs, Maya, ESRI, and many more. Almost every organization doing software development uses Python in some fashion, whether for long-term strategic product development or for short-term tactical tasks such as testing and system administration.

  3. Python’s downside is performance: it won’t run as quickly as fully compiled languages like C and C++. On the other hand, it’s quick enough for most applications, and typical Python code runs at close to C speed anyhow because it invokes linked-in C code in the interpreter. If speed is critical, compiled extensions are available for number-crunching parts of an application.

  4. You can use Python for nearly anything you can do with a computer, from website development and gaming to robotics and spacecraft control.

  5. import this triggers an Easter egg inside Python that displays some of the design philosophies underlying the language. You’ll learn how to run this statement in the next chapter.

  6. “Spam” is a reference from a famous Monty Python skit in which people trying to order food in a cafeteria are drowned out by a chorus of Vikings singing about spam. Oh, and it’s also a common variable name in Python scripts....

  7. Blue. No, yellow!



[2] For a more complete look at the Python philosophy, type the command import this at any Python interactive prompt (you’ll see how in Chapter 2). This invokes an “Easter egg” hidden in Python—a collection of design principles underlying Python. The acronym EIBTI is now fashionable jargon for the “explicit is better than implicit” rule.

The best content for your career. Discover unlimited learning on demand for around $1/day.