Generators yield for faster processing
Generators look like functions in fact, they are a special kind of function. They use the yield statement to return data whereas regular functions use the return statement . Generators are a convenient way to create iterators because they simplify the record-keeping needed for returning each element. That is, you don't have to keep checking and reassigning values because the generator remembers the values it was assigned last. Generators are different from functions in two other ways Calling a...
Importing items from inside a module
Importing items from inside a module stores their names in the namespace, which gives you direct access to the items you don't have to type the module name to use them. But this method doesn't store the name of the module in the namespace. To import the function that's inside tinymodule, type this gt gt gt from tinymodule import tinyfunction To check what's stored in the namespace, type dir . Note If you didn't quit Python after doing the example in the previous section, Importing by name, you...
Working with a ZipFile object
ZipFile instances are similar to file objects. They have these methods close and read Work like the file object methods of the same names see Chapter 17 . getinfo Takes a string specifying the name of an item in the archive and returns a Zipinfo object containing information about the item. gt gt gt myz.getinfo 'pagecount.py' lt zipfile.ZipInfo instance at 0x79fa8 gt One way to see the attributes of the Zipinfo object is to use the dir function. The following example looks at the contents of a...
Calling in the Borg Pattern
You can make a special kind of class so that all of its instances share the same state which makes them functionally identical . That means whatever you do to one instance is also done to all the other instances. Tip To create this class, use the following brilliant code from Alex Martelli called the Borg Pattern Here's what happens when you test it. This code shows that the two Borg instances are different objects they are stored in different locations gt gt gt borg1 Config gt gt gt borg2...
Its easier to ask forgiveness than permission
Early in the history of programming, errors were often handled by trying to guess every error that might occur and then writing a lot of if statements to process them. This philosophy of error handling is called Look Before You Leap LBYL for short . This is expensive in computer processing power because the error checking occurs every time the user does something enters data, clicks something on the screen, chooses from a menu, and so on . The try statement lets you assume that users will use...
Collecting Globs and Globs of Files
The glob module provides a single function, also called glob, which lets you get a list of files from a directory you can also find directory names . The glob function recognizes the same wildcard search characters that the UNIX shell recognizes, except for tilde . TECHNICAL On Mac and Unix systems, glob searches are case-sensitive. STUFF Here's how to find all the Word documents which end with the suffix .doc in a directory called MyDocs gt gt gt docs glob.glob 'MyDocs .doc' 'MyDocs...
Zipping up a Python library
PyZipFile instances create zip archives containing Python libraries. Python can import modules from Zip files. Putting the modules your program uses into Zip files is one way of delivering a smaller program. To create a zip archive with Python files, follow these steps 1. Create a PyZipFile instance. Use the instructions in Creating a ZipFile object for reading or writing, earlier in this chapter. Open the archive for writing or appending. Your code will look something like this mypz...
The inner lives of iterators
Iterators are used throughout Python, and if you understand them, you will have a good grasp on what Python is all about. An iterator is a Python object that produces elements one at a time. An iterable is an object that can create an iterator. For example, the iterator created from a list returns the list elements one at a time, in order. The iterator for a dict returns the keys one at a time, unordered. Lists and dicts are examples of iterables. As if things weren't confusing enough, some...
Expression and Comprehension Listcomps and Genexps
List comprehensions listcomps and generator expressions genexps let you focus on data rather than control structures. See also the Focusing on Functions section, later in this chapter. They replace a for loop with an expression. List comprehension and generator expression code can look intimidating if you don't know what's going on. But after you get used to them, you'll probably find them a lot easier and quicker to use than the multi-line statements they replace. Remember that you never have...
Generator expressions
In the earlier section, Generators yield for faster processing, we discuss generators, which are a special kind of function that makes processing in loops more efficient. Python 2.4 introduces generator expressions. Generator expressions genexps for short are a shorthand way of creating generator iterators. Genexps look like listcomps, but they use parentheses rather than brackets. However, if the generator expression is the only argument of a function, you can skip the parentheses. The...
Why modularizing is a good idea
Why doesn't Python automatically import all of its built-in modules First of all, importing all of its modules would take a LOOOONG time. Second, if it did, there would be thousands of names stored in the namespace, and you wouldn't be able to give those names to your own data or if you did use them, you might get unexpected results. Because you need to import modules, stuff you don't use stays out of your way, like storing your winter clothes in the attic until October. Whoa That's a lot of...
Example of a custom TextWrapper object
Here's an example of a custom TextWrapper object. This object specifies a 40-character line and indents each line after the first one 4 spaces. gt gt gt mywrapper textwrap.TextWrapper width 4 0, subsequent indent gt gt gt indented string mywrapper.fill longstring gt gt gt print indented string But once you build some islands of peace into your daily routine, they help serve as beachheads against the full-court press of life. --Mixed Metaphor Hall of Fame
Getting Close Enough with difflib
People often make mistakes when entering text. The difflib module gives you a way to find strings that are close but not exact matches to a given string gt gt gt right 'The quick brown fox' gt gt gt wrong 'THe quack brown fix' gt gt gt matcher difflib.SequenceMatcher None, right, wrong The ratio method returns a floating point number between 0 and 1 that indicates how close the match is. Higher numbers indicate a closer match. A match higher than 0.6 is usually considered good maybe not by...
Debugging in IDLE
When you run code in IDLE's interactive mode, it informs you of errors the same way you've seen when using interactive mode in a Terminal or shell window. When you run code from the text editor, IDLE also informs you of errors. Depending on the kind of error and on your version of IDLE, the error message appears in a dialog box or in the Python Shell window. You can use the IDLE debugger to step through your program in various ways and display the values of names. The IDLE debugger is shown in...
Encoding binary data into string data
The Encoders module includes functions for turning binary data into data that can be sent as e-mail. Two of its functions are encode_quopri Use for a message that has mostly text but some unprintable characters. encode_base64 Use for a message that has mostly binary unprintable data. The format is more compact than quoted-printable, but humans can't read it. The encoding functions add a Content-Transfer-Encoding header. They change a message in place and return None. To encode the Message...