Text
stringlengths
1
9.41k
This structure is also why Python lends itself to product customization—because Python code can be changed on the fly, users can modify the Python parts of a system onsite without needing to have or compile the entire system’s code. At a more fundamental level, keep in mind that all we really have in Python is runtime...
This even includes operations such as the creation of functions and classes and the linkage of modules.
Such events occur before execution in more static languages, but happen as programs execute in Python.
As we’ll see, the net effect makes for a much more dynamic programming experience than that to which some readers may be accustomed. **|** ----- ###### Execution Model Variations Before moving on, I should point out that the internal execution flow described in the prior section reflects the standard implementatio...
Because of that, the execution model is prone to changing with time. In fact, there are already a few systems that modify the picture in Figure 2-2 somewhat.
Let’s take a few moments to explore the most prominent of these variations. ###### Python Implementation Alternatives Really, as this book is being written, there are three primary implementations of the Python language—CPython, Jython, and IronPython—along with a handful of secondary implementations such as Stackles...
In brief, CPython is the standard implementation; all the others have very specific purposes and roles.
All implement the same Python language but execute programs in different ways. ###### CPython The original, and standard, implementation of Python is usually called CPython, when you want to contrast it with the other two.
Its name comes from the fact that it is coded in portable ANSI C language code.
This is the Python that you fetch from http://www _.python.org, get with the ActivePython distribution, and have automatically on most_ Linux and Mac OS X machines.
If you’ve found a preinstalled version of Python on your machine, it’s probably CPython, unless your company is using Python in very specialized ways. Unless you want to script Java or .NET applications with Python, you probably want to use the standard CPython system.
Because it is the reference implementation of the language, it tends to run the fastest, be the most complete, and be more robust than the alternative systems.
Figure 2-2 reflects CPython’s runtime architecture. ###### Jython The Jython system (originally known as JPython) is an alternative implementation of the Python language, targeted for integration with the Java programming language. Jython consists of Java classes that compile Python source code to Java byte code and ...
Programmers still code Python statements in .py text files as usual; the Jython system essentially just replaces the rightmost two bubbles in Figure 2-2 with Java-based equivalents. Jython’s goal is to allow Python code to script Java applications, much as CPython allows Python to script C and C++ components.
Its integration with Java is remarkably seamless. Because Python code is translated to Java byte code, it looks and feels like a true Java program at runtime.
Jython scripts can serve as web applets and servlets, build Java-based GUIs, and so on.
Moreover, Jython includes integration support that allows **|** ----- Python code to import and use Java classes as though they were coded in Python. Because Jython is slower and less robust than CPython, though, it is usually seen as a tool of interest primarily to Java developers looking for a scripting language ...
.NET and its C# programming language runtime system are designed to be a language-neutral object communication layer, in the spirit of Microsoft’s earlier COM model.
IronPython allows Python programs to act as both client and server components, accessible from other .NET languages. By implementation, IronPython is very much like Jython (and, in fact, was developed by the same creator)—it replaces the last two bubbles in Figure 2-2 with equivalents for execution in the .NET environ...
Also, like Jython, IronPython has a special focus—it is primarily of interest to developers integrating Python with .NET components.
Because it is being developed by Microsoft, though, IronPython might also be able to leverage some important optimization tools for better performance. IronPython’s scope is still evolving as I write this; for more details, consult the Python online resources or search the Web.[†] ###### Execution Optimization Tools ...
Still other systems, including the Psyco just-in-time compiler and the Shedskin C++ translator, instead attempt to optimize the basic execution model.
These systems are not required knowledge at this point in your Python career, but a quick look at their place in the execution model might help demystify the model in general. ###### The Psyco just-in-time compiler The Psyco system is not another Python implementation, but rather a component that extends the byte cod...
In terms of Figure 2-2, Psyco is an enhancement to the PVM that collects and uses type information while the program runs to translate portions of the program’s byte code all the way down to real binary machine code for faster execution.
Psyco accomplishes this † Jython and IronPython are completely independent implementations of Python that compile Python source for different runtime architectures.
It is also possible to access Java and .NET software from standard CPython programs: JPype and Python for .NET systems, for example, allow CPython code to call out to Java and .NET components. **|** ----- translation without requiring changes to the code or a separate compilation step during development. Roughly, ...
Once generated, the machine code then replaces the corresponding part of the original byte code to speed your program’s overall execution.
The net effect is that, with Psyco, your program becomes much quicker over time and as it is running.
In ideal cases, some Python code may become as fast as compiled C code under Psyco. Because this translation from byte code happens at program runtime, Psyco is generally known as a just-in-time (JIT) compiler.
Psyco is actually a bit different from the JIT compilers some readers may have seen for the Java language, though.
Really, Psyco is a specializing JIT compiler—it generates machine code tailored to the data types that your program actually uses.
For example, if a part of your program uses different data types at different times, Psyco may generate a different version of machine code to support each different type combination. Psyco has been shown to speed Python code dramatically.
According to its web page, Psyco provides “2x to 100x speed-ups, typically 4x, with an unmodified Python interpreter and unmodified source code, just a dynamically loadable C extension module.” Of equal significance, the largest speedups are realized for algorithmic code written in pure Python—exactly the sort of code ...
For more details on the Psyco extension, and other JIT efforts that may arise, consult http://www.python.org; you can also check out Psyco’s home page, which currently resides at http://psyco.sourceforge.net. ###### The Shedskin C++ translator Shedskin is an emerging system that takes a different approach to Python p...
As such, it represents a platformneutral approach to running Python code.
Shedskin is still somewhat experimental as I write these words, and it limits Python programs to an implicit statically typed constraint that is technically not normal Python, so we won’t go into further detail here. **|** ----- Initial results, though, show that it has the potential to outperform both standard Pyt...
With the help of third-party tools that you can fetch off the Web, it is possible to turn your Python programs into true executables, known as frozen bi_naries in the Python world._ Frozen binaries bundle together the byte code of your program files, along with the PVM (interpreter) and any Python support files your p...
There are some variations on this theme, but the end result can be a single binary executable program (e.g., an .exe file on Windows) that can easily be shipped to customers.
In Figure 2-2, it is as though the byte code and PVM are merged into a single component—a frozen binary file. Today, three primary systems are capable of generating frozen binaries: py2exe (for Windows), PyInstaller (which is similar to py2exe but also works on Linux and Unix and is capable of generating self-installi...
You may have to fetch these tools separately from Python itself, but they are available free of charge.
They are also constantly evolving, so consult http://www.python.org or your favorite web search engine for more on these tools.
To give you an idea of the scope of these systems, py2exe can freeze standalone programs that use the tkinter, PMW, wxPython, and PyGTK GUI libraries; programs that use the pygame game programming toolkit; win32com client programs; and more. Frozen binaries are not the same as the output of a true compiler—they run by...
Hence, apart from a possible startup improvement, frozen binaries run at the same speed as the original source files.
Frozen binaries are not small (they contain a PVM), but by current standards they are not unusually large either. Because Python is embedded in the frozen binary, though, it does not have to be installed on the receiving end to run your program.
Moreover, because your code is embedded in the frozen binary, it is more effectively hidden from recipients. This single file-packaging scheme is especially appealing to developers of commercial software.
For instance, a Python-coded user interface program based on the tkinter toolkit can be frozen into an executable file and shipped as a self-contained program on a CD or on the Web.
End users do not need to install (or even have to know about) Python to run the shipped program. **|** ----- ###### Other Execution Options Still other schemes for running Python programs have more focused goals: - The Stackless Python system is a standard CPython implementation variant that does not save state ...
This makes Python more easy to port to small stack architectures, provides efficient multiprocessing options, and fosters novel programming structures such as coroutines. - The Cython system (based on work done by the Pyrex project) is a hybrid language that combines Python code with the ability to call C functions a...
Cython code can be compiled to C code that uses the Python/C API, which may then be compiled completely.
Though not completely compatible with standard Python, Cython can be useful both for wrapping external C libraries and for coding efficient C extensions for Python. For more details on these systems, search the Web for recent links. ###### Future Possibilities? Finally, note that the runtime execution model sketched...
For instance, it’s not impossible that a full, traditional compiler for translating Python source code to machine code may appear during the shelf life of this book (although one has not in nearly two decades!).
New byte code formats and implementation variants may also be adopted in the future.
For instance: - The Parrot project aims to provide a common byte code format, virtual machine, and optimization techniques for a variety of programming languages (see http:// _www.python.org).
Python’s own PVM runs Python code more efficiently than Par-_ rot, but it’s unclear how Parrot will evolve. - The PyPy project is an attempt to reimplement the PVM in Python itself to enable new implementation techniques.
Its goal is to produce a fast and flexible implementation of Python. - The Google-sponsored Unladen Swallow project aims to make standard Python faster by a factor of at least 5, and fast enough to replace the C language in many contexts.
It is an optimization branch of CPython, intended to be fully compatible and significantly faster.
This project also hopes to remove the Python multithreading Global Interpreter Lock (GIL), which prevents pure Python threads from truly overlapping in time.
This is currently an emerging project being developed as open source by Google engineers; it is initially targeting Python 2.6, though 3.0 may acquire its changes too.
Search Google for up-to-date details. Although such future implementation schemes may alter the runtime structure of Python somewhat, it seems likely that the byte code compiler will still be the standard for **|** ----- some time to come.
The portability and runtime flexibility of byte code are important features of many Python systems.
Moreover, adding type constraint declarations to support static compilation would break the flexibility, conciseness, simplicity, and overall spirit of Python coding.
Due to Python’s highly dynamic nature, any future implementation will likely retain many artifacts of the current PVM. ###### Chapter Summary This chapter introduced the execution model of Python (how Python runs your programs) and explored some common variations on that model (just-in-time compilers and the like).
Although you don’t really need to come to grips with Python internals to write Python scripts, a passing acquaintance with this chapter’s topics will help you truly understand how your programs run once you start coding them.
In the next chapter, you’ll start actually running some code of your own. First, though, here’s the usual chapter quiz. ###### Test Your Knowledge: Quiz 1. What is the Python interpreter? 2.
What is source code? 3. What is byte code? 4. What is the PVM? 5. Name two variations on Python’s standard execution model. 6.
How are CPython, Jython, and IronPython different? ###### Test Your Knowledge: Answers 1. The Python interpreter is a program that runs the Python programs you write. 2.
Source code is the statements you write for your program—it consists of text in text files that normally end with a .py extension. 3.
Byte code is the lower-level form of your program after Python compiles it. Python automatically stores byte code in files with a .pyc extension. 4.
The PVM is the Python Virtual Machine—the runtime engine of Python that interprets your compiled byte code. 5. Psyco, Shedskin, and frozen binaries are all variations on the execution model. 6.
CPython is the standard implementation of the language.
Jython and IronPython implement Python programs for use in Java and .NET environments, respectively; they are alternative compilers for Python. **|** ----- ###### CHAPTER 3 ### How You Run Programs OK, it’s time to start running some code.
Now that you have a handle on program execution, you’re finally ready to start some real Python programming.
At this point, I’ll assume that you have Python installed on your computer; if not, see the prior chapter and Appendix A for installation and configuration hints. There are a variety of ways to tell Python to execute the code you type.
This chapter discusses all the program launching techniques in common use today.
Along the way, you’ll learn how to type code interactively and how to save it in files to be run with system command lines, icon clicks, module imports and reloads, exec calls, menu options in GUIs such as IDLE, and more. If you just want to find out how to run a Python program quickly, you may be tempted to read the ...
But don’t skip the material on module imports, as that’s essential to understanding Python’s program architecture.
I also encourage you to at least skim the sections on IDLE and other IDEs, so you’ll know what tools are available for when you start developing more sophisticated Python programs. ###### The Interactive Prompt Perhaps the simplest way to run Python programs is to type them at Python’s interactive command line, somet...
There are a variety of ways to start this command line: in an IDE, from a system console, and so on.
Assuming the interpreter is installed as an executable program on your system, the most platformneutral way to start an interactive interpreter session is usually just to type python at your operating system’s prompt, without any arguments.
For example: ----- ``` % python Python 3.0.1 (r301:69561, Feb 13 2009, 20:04:18) [MSC v.1500 32 bit (Intel)] ... Type "help", "copyright", "credits" or "license" for more information. >>> ``` Typing the word “python” at your system shell prompt like this begins an interactive Python session; the “%” charact...
The notion of a system shell prompt is generic, but exactly how you access it varies by platform: - On Windows, you can type python in a DOS console window (a.k.a.
the Command Prompt, usually found in the Accessories section of the Start→Programs menu) or in the Start→Run...
dialog box. - On Unix, Linux, and Mac OS X, you might type this command in a shell or terminal window (e.g., in an xterm or console running a shell such as ksh or csh). - Other systems may use similar or platform-specific devices.
On handheld devices, for example, you generally click the Python icon in the home or application window to launch an interactive session. If you have not set your shell’s PATH environment variable to include Python’s install directory, you may need to replace the word “python” with the full path to the Python executab...
On Unix, Linux, and similar, `/usr/local/bin/python` or /usr/bin/python will often suffice.
On Windows, try typing C:\Python30\python (for version 3.0): ``` C:\misc> c:\python30\python Python 3.0.1 (r301:69561, Feb 13 2009, 20:04:18) [MSC v.1500 32 bit (Intel)] ... Type "help", "copyright", "credits" or "license" for more information. >>> ``` Alternatively, you can run a change-directory command to g...
Both spawn a Python interactive prompt with equivalent functionality; typing a shell command isn’t necessary. **|** ----- ###### Running Code Interactively However it’s started, the Python interactive session begins by printing two lines of informational text (which I’ll omit from most of this book’s examples to s...
When working interactively, the results of your code are displayed after the >>> lines after you press the Enter key. For instance, here are the results of two Python `print statements (print is really a` function call in Python 3.0, but not in 2.6, so the parentheses here are required in 3.0 only): ``` % python >...
In short, they print a Python string and an integer, as shown by the output lines that appear after each >>> input line (2 ** 8 means 2 raised to the power 8 in Python). When coding interactively like this, you can type as many Python commands as you like; each is run immediately after it’s entered.
Moreover, because the interactive session automatically prints the results of expressions you type, you don’t usually need to say “print” explicitly at this prompt: ``` >>> lumberjack = 'okay' >>> lumberjack 'okay' >>> 2 ** 8 256 >>> <== Use Ctrl-D (on Unix) or Ctrl-Z (on Windows) to exit % ``...
To exit an interactive session like this one and return to your system shell prompt, type Ctrl-D on Unix-like machines; on MS-DOS and Windows systems, type Ctrl-Z to exit. In the IDLE GUI discussed later, either type Ctrl-D or simply close the window. Now, we didn’t do much in this session’s code—just typed some Pytho...
There was no need to create a source-code file, and no need to run the code through a compiler and linker first, as you’d normally do when using a language such as C or C++.
As you’ll see in later chapters, you can also run multiline statements at the interactive prompt; such a statement runs immediately after you’ve entered all of its lines and pressed Enter twice to add a blank line. ###### Why the Interactive Prompt? The interactive prompt runs code and echoes results as you go, but i...
Although this means you won’t do the bulk of your coding in interactive sessions, the interactive prompt turns out to be a great place to both experiment with the language and test program files on the fly. ###### Experimenting Because code is executed immediately, the interactive prompt is a perfect place to experim...
In fact, this is the first rule of thumb to remember: if you’re ever in doubt about how a piece of Python code works, fire up the interactive command line and try it out to see what happens. For instance, suppose you’re reading a Python program’s code and you come across an expression like 'Spam!' * 8 whose meaning yo...
At this point, you can spend 10 minutes wading through manuals and books to try to figure out what the code does, or you can simply run it interactively: `>>> 'Spam!' * 8` _<== Learning by trying_ ``` 'Spam!Spam!Spam!Spam!Spam!Spam!Spam!Spam!' ``` The immediate feedback you receive at the interactive prompt is ofte...
Here, it’s clear that it does string repetition: in Python * means multiply for numbers, but repeat for strings—it’s like concatenating a string to itself repeatedly (more on strings in Chapter 4). Chances are good that you won’t break anything by experimenting this way—at least, not yet.
To do real damage, like deleting files and running shell commands, you must really try, by importing modules explicitly (you also need to know more about Python’s system interfaces in general before you will become that dangerous!).
Straight Python code is almost always safe to run. For instance, watch what happens when you make a mistake at the interactive prompt: **|** ----- `>>> X` _<== Making mistakes_ ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'X' is not defined ``` In Python, using...
We’ll learn more about that later; the important point here is that you don’t crash Python or your computer when you make a mistake this way.