Access Model

Although the previous two models of categorizing the types are useful when being introduced to Python, they are not the primary models for differentiating the types. For that purpose, we use the access model. By this, we mean, how do we access the values of our stored data There are three categories under the access model direct, sequence, and mapping. The different access models and which types fall into each respective category are Table 4.8. Types Categorized by the Access Model Table 4.8....

Builtin Methods

Table 7.1 lists the methods for dictionary objects. The clear(), copy(), get(), and update() methods were added recently in Python 1.5. setdefault() was introduced in 2.0. removes all elements of dictionary diet returns a (shallow M ) copy of dictionary diet for key key, returns value or default if key not in dictionary (note that defaults default is None) returns 1 if key in dictionary diet, 0 otherwise returns a list of diets (key, value) tuple pairs returns list of dictionary diet's keys...

Creating a TCP Server

We will first present some general pseudocode involved with creating a generic TCP server, then describe in general what is going on. Keep in mind that this is only one way of designing your server. Once you become comfortable with server design, you will be able to modify the pseudocode to operate the way you want it to ss socket() ss.bind() ss.listen() inf_loop cs.recv() cs.send() cs.close() ss.close() All sockets are created using the socket.socket() function. Servers need to sit on a port...

Else Statement Take

In C (as well as in most other languages), you will not find an else statement outside the realm of conditional statements, yet Python bucks the trend again by offering these in while or for loops. How do they work When used with loops, an else clause will be executed only if a loop finishes to completion, meaning they were not abandoned by break. One popular example of else usage in a while statement is in finding the largest factor of a number. We have implemented a function which performs...

Example Dynamically Generating and Executing Python Code loopmakepy

Ltype raw input('Loop type (For While) ') dtype raw input('Data type (Number Seq) ') stop input('Ending value (non-inclusive) var raw input('Iterative variable name ') exec str exec dict 'f' (var, seq, var) svar raw input('Enter sequence name (var, svar, seq, var, svar, svar, var, var, var (var, start, var, stop, var, var, var, step) print 'Your custom-generated code ' + dashes print 'Test execution of the code ' + dashes Here are a few example executions of this script The custom-generated...

Executable Object Statements and Builtin Functions

Python provides a number of built-in functions supporting callables and executable objects, including the exec statement. These functions let the programmer execute code objects as well as generate them using the compile() built-in function and are listed in Table 14.6. Table 14.6. Executable Object Statements and Built-in Functions Table 14.6. Executable Object Statements and Built-in Functions determines if obj is callable returns 1 if so, 0 otherwise creates a code object from string of type...

Figure Python Win Environment in Windows

More documentation from the installed software can be found by firing up your web browser and pointing it to the following location (or wherever your PythonWin is installed) file C Program Files Python Pythonwin readme.html As we mentioned before, IDLE is also available on the Windows platform, due to the portability of Tcl Tk and Python Tkinter. It looks similar to its Unix counterpart (Figure1-5).

File Builtin Function [open

As the key to opening file doors, the open() built-in function provides a general interface to initiate the file input output (I O) process. open() returns a file object on a successful opening of the file or else results in an error situation. When a failure occurs, Python generates or raises an IOError exception we will cover errors and exceptions in the next chapter. The basic syntax of the open() built-in function is file_object open(file_name, access_mode ,r,r buffering -1) The file_name...

First Python Application

Now that we are familiar with the syntax, style, variable assignment and memory allocation, it is time to look at a more complex example of Python programming. Many of the things in this program will be parts of Python which may have unfamiliar constructs, but we believe that Python is so simple and elegant that the reader should be able to make the appropriate conclusions upon examination of the code. The source file we will be looking at is fgrepwc.py, named in honor of the two Unix utilities...

GUIs with Python development interfaces

Glade (GTK+ UI builder) http glade.pn.org 3. GLC (Glade Python Code Generator) http glc.sourceforge.net 4. GTK+ (GIMP Toolkit) http www.gtk.org 5. KDE (K Desktop Environment) http www.kde.org 6. PMW (Python MegaWidgets for Tkinter) http www.dscpl.com.au pmw 7. PyG Tools (PyGTK, PyGNOME, etc.) 10. Python-KDE Tutorial 11. Tkinter (Python-Tk) 12. Tkinter intro (F. Lundh) 13. TrollTech Qt products (commercial) http www.trolltech.com products 14. wxPython http www.wxpython.org

In either case a servers work is never done

The teller is, of course, the server that runs in an infinite loop. Each customer is a client with a need which requires servicing. Customers arrive and are serviced by the teller in a first-come-first-served manner. Once a transaction has been completed, the client goes away while the server either serves the next customer or sits and waits until one comes along. Why is all this important The reason is that this style of execution is how client-server architecture works in a general sense. Now...

In this example we pass in a callable class instance as opposed to just a function It presents more of an OO approach

Def init (self, func, args, name '') print 'start loop', nloop, 'at ', ctime(time print 'loop', nloop, 'done at ', ctime(time( for i in nloops create all threads target ThreadFunc(loop, (i, loops i i for i in nloops start all threads for i in nloops wait for completion When the Thread code calls our ThreadFunc object when a new thread is created, it will invoke the_call_() special method. Because we already have our set of arguments, we do not need to pass it to the Thread() constructor, but do...

Intermediate Tkinter Example

We conclude this section with a larger example, listdir.py. This application is a directory tree traversal tool. It starts in the current directory and provides a file listing. Double-clicking on any other directory in the list causes the tool to change to the new directory as well as replace the original file listing with the files from the new directory. The source code is given below as Example 18.5. Example 18.5. File System Traversal GUI (listdir.py) This slightly more advanced GUI expands...

Introduction About OOP

Before we get into the nitty-gritty of OOP and classes, we begin with a high-level overview, then present some simple examples to get you warmed up. If you are new to object-oriented programming, you may wish to merely skim this section first, then begin the formal reading in Section 13.2. This section is targeted more to those already familiar with the concepts, who simply want to see how it's done in Python. The main two entities in Python object-oriented programming are classes and class...

Introduction to GUI Programming

Before going to the examples, we will give you a brief introduction to GUI application development in general. This will give you some of the background you need to move forward. Setting up a GUI application is similar to an artist's producing a painting. Conventionally, there is a single canvas onto which the artist must put all the work. The way it works is like this You start with a clean slate, a top-level windowing object on which you build the rest of your components. Think of it as a...

Introduction Motivation

Manipulating text data is a big thing. If you don't believe me, look very carefully at what computers primarily do today. Word processing, fill-out-form Web pages, streams of information coming from a database dump, stock quote information, news feeds the list goes on and on. Because we may not know the exact text or data which we have programmed our machines to process, it becomes advantageous to be able to express this text or data in patterns which a machine can recognize and take action...

Iterating by Sequence Index

An alternative way of iterating through each item is by index offset into the sequence itself > > > nameList 'Shirley', Terry, 'Joe', 'Heather', 'Lucy' > > > for namelndex in range(len(nameList)) print Liu,, nameList nameIndex Rather than iterating through the elements themselves, we are iterating through the indices of the list. We employ the assistance of the len() built-in function, which provides the total number of elements in the tuple as well as the range() built-in function...

List Type Builtin Methods

We will go over methods more formally in an introduction to object-oriented programming in Chapter 13, but for now, think of methods as functions or procedures that apply only to specific objects. So the methods described in this section behave just like built-in functions except that they operate only on lists. Since these functions involve the mutability (or updating) of lists, none of them is applicable for tuples. You may recall our earlier discussion of...

Mixed Mode Operations

It may be hard to remember, but when you added a pair of numbers in the past, what was important was that you got your numbers correct. Addition using the plus ( + ) sign was always the same. In programming languages, this may not be as straightforward because there are different types of numbers. When you add a pair of integers, the + represents integer addition, and when you add a pair of floating point numbers, the + represents double-precision floating point addition, and so on. Our little...

Name Lookup Scoping and Overriding

So how do scoping rules work in relationship to namespaces It all has to do with name lookup. When accessing an attribute, the interpreter must find it in one of the three namespaces. The search begins with the local namespace. If the attribute is not found there, then the global namespace is searched. If that is also unsuccessful, the final frontier is the built-ins namespace. If the exhaustive search fails, you get the familiar File < stdin> , line 1, in NameError foo Notice how the...

Namespaces vs Variable Scope

Okay, now that we know what namespaces are, how do they relate to variable scope again They seem extremely similar. The truth is, you are quite correct. Namespaces are purely mappings between names and objects, but scope dictates how or rather, where, one can access these names based on the physical location from within your code. We illustrate the relationship between namespaces and variable scope in Figure 12-1. Figure 12.1. Namespaces vs. Variable Scope Figure 12.1. Namespaces vs. Variable...

Object Identity Comparison

In addition to value comparisons, Python also supports the notion of directly comparing objects themselves. Objects can be assigned to other variables (by reference). Because each variable points to the same (shared) data object, any change effected through one variable will change the object and hence be reflected through all references to the same object. In order to understand this, you will have to think of variables as linking to objects now and be less concerned with the values...

Python Operator Summary

TableC.1 represents the complete set of Python operators and to which standard types they apply. The operators are sorted from highest-to-lowest precedence, with those sharing the same shaded group having the same priority. Table c.1. Python Operators (t - unary) Table c.1. Python Operators (t - unary) Delivered for Maurice ling Swap Option Available 7 15 2002 Last updated on 9 14 2001 Core Python Programming, 2002 Prentice Hall PTR Delivered for Maurice ling Swap Option Available 7 15 2002...

Rather than using a call to sleep to hold up the main thread as in mtsleepipy the use of locks makes more sense

Thread.start_new_thread(loop, (i, loops i , locks i )) while locks i .locked() pass < nopage> So how did we accomplish our task with locks Let's take a look at the source code Line-by-line explanation After the Unix start-up line, we import the thread module and a few familiar attributes of the time module. Rather than hardcoding separate functions to count to 4 and 2 seconds, we will use a single loop() function and place these constants in a list, loops. The loop() function will proxy for...

Related Modules and Other GUIs

There are other GUI development systems which can be used with Python. We present the appropriate modules along with their corresponding window systems in Table 18.2. Table 18.2. GUI Systems Available Under Python Table 18.2. GUI Systems Available Under Python Delivered for Maurice ling Last updated on 9 14 2001 Swap Option Available 7 15 2002 Core Python Programming, 2002 Prentice Hall PTR < BACK Make Note Bookmark CONTINUE > Delivered for Maurice ling Last updated on 9 14 2001 Swap Option...

Search vs Match

Before we create any REs, however, we realize that these integer data items are at the end of the data strings. This means that we have a choice of using either search or match. Initiating a search makes more sense because we know exactly what we are looking for (set of 3 integers), that what we seek is not at the beginning of the string, and that it does not make up the entire string. If we were to perform a match, we would have to create an RE to match the entire line and use subgroups to...

Secure Socket Layer support

The urllib module has been modified for Python 1.6 so that it now supports opening HTTP connections using the Secure Socket Layer (SSL). The core change to add SSL is implemented in the socket module. Consequently, the urllib and httplib modules were updated to support URLs using the https connection scheme. Note, however, that as of time of publication, only HTTP requests using SSL have been implemented. The future may see additional updates to the other protocols supported by the urllib...

Shallow and Deep Copies

Earlier in Section 3.5, we described how object assignments are simply object references. This means that when you create an object, then assign that object to another variable, Python does not copy the object. Instead, it copies only a reference to the object. For example > > > aList 78, 'pyramid' , 84, 'vulture' , 81, 'eye' > > > anotherList aList > > > aList 78, 'pyramid' , 84, 'vulture' , 81, 'eye' 78, 'pyramid' , 84, 'vulture' , 81, 'eye' Above, a list of two elements is...

Socket Addresses Hostport Pairs

If a socket is like a telephone jack, a piece of infrastructure that enables communication, then a hostname and port number are like an area code and telephone number combination. Having the hardware and ability to communicate doesn't do any good unless you know whom and where to dial. An Internet address is comprised of a hostname and port number pair, and such an address is required for networked communication. It goes without saying that there should also be someone listening at the other...

Standard Type Builtin Functions

Along with generic operators which we have just seen, Python also provides some built-in functions that can be applied to all the basic object types cmp(), repr(), str(), type(), and the single reverse or back quotes ( 11 ) operator, which is functionally-equivalent to repr(). Table 4.4. Standard Type Built-in Functions Table 4.4. Standard Type Built-in Functions compares obj1 and obj2, returns integer i where i < 0 if obj1 < obj2 i > 0 if obj1 > obj2 i 0 if obj1 obj2 returns...

Testit invokes a given function with its arguments returning a packaged with the return value of the function on

Retval apply(func, nkwargs, kwargs) vals (1234, 12.34, '1234', '12.34') (eachFunc. name , 'eachVal'), retval 1 (eachFunc. name , 'eachVal'), retval 1 The unit tester function test() runs a set of numeric conversion functions on of four numbers. There are two failure cases in this test set to confirm such functionality. Here is the output of running the script of four numbers. There are two failure cases in this test set to confirm such functionality. Here is the output of running the script...

This script calls the who command and parses the input by splitting up its data along various types of whitespace

0 03 3 from os import popen 004 4 from re import split 008 8 for eachLine in map(strip, f.readlines()) 009 9 print split(' s s+ t', eachLine) Running this script, we now get the following (correct) output A similar exercise can be achieved in a DOS Windows environment using the dir command in place of who. You may have seen the use of raw strings in some of the examples above. Regular expressions were a strong motivation for the advent of raw strings. The reason is because of conflicts between...

This simple script uses lists as a queue to store and retrieve strings entered through this menudriven text application

Queue.appendiraw inputi'Enter new string ')) print 'Cannot dequeue from empty queue ' print 'Removed ', queue.pop(0), ' ' except (EOFError, Keyboardlnterrupt) print 'invalid option, try again else < nopage> chosen 1 if choice if choice if choice if choice Because of the similarities of this script with the stack.py script, we will describe only in detail the lines which have changed significantly The enQ() function works exactly like pushit(), only the name has been changed. The key...

This simple script uses lists as a stack to store and retrieve strings entered through this menudriven text application

From an empty stack stack.pop(), ' ' from an empty stack stack.pop(), ' ' except (EOFError, Keyboardlnterrupt) In addition to the Unix startup line, we take this opportunity to clear the stack (a list). Lines 5-6 The pushit() function adds an element (a string prompted from the user) to the stack. Lines 8-12 The popit() function removes an element from the stack (the more recent one). An error occurs when trying to remove an element from an empty stack. In this case, a warning is sent back to...

Urllib Module NOTE

Unless you are planning on writing a more lower-level neWork client, the urllib module provides all the functionality you need. urllib provides a high-level Web communication library, supporting the basic Web protocols, HTTP, FTP, and Gopher, as well as providing access to local files. Specifically the functions of the urllib module are designed to download data (from the Internet, local neWork, or local host) using the aforementioned protocols. Use of this module generally obviates the need...

Uniform Resource Locators

Simple Web surfing involves using Web addresses called Uniform Resource Locators (URLs). Such addresses are used to locate a document on the Web or to call a CGI program to generate a document for your client. URLs are part of a larger set of identifiers known as URIs (Uniform Resource Identifiers). This superset was created in anticipation of other naming conventions which have yet to be developed. A URL is simply a URI which uses an existing protocol or scheme (i.e., http, ftp, etc.) as part...

Repetition special characters and grouping

The most common aspects of REs involve the use of special characters, multiple occurrences of RE patterns, and using parentheses to group and extract submatch patterns. One particular RE we looked at related to simple e-mail addresses ( w+ w+ .com). Perhaps we want to match more e-mail addresses than this RE allows. In order to support an additional hostname in front of the domain, i.e., www.xxx.com as opposed to accepting only xxx.com as the entire domain, we have to modify our existing RE. To...