Text
stringlengths
1
9.41k
What makes generators so compact is that the __iter__() and __next__() methods are created automatically. Another key feature is that the local variables and execution state are automatically saved between calls. This made the function easier to write and much more clear than an approach using instance variables like ...
In combination, these features make it easy to create iterators with no more effort than writing a regular function. ### 9.10 Generator Expressions Some simple generators can be coded succinctly as expressions using a syntax similar to list comprehensions but with parentheses instead of square brackets.
These expressions are designed for situations where the generator is used right away by an enclosing function.
Generator expressions are more compact but less versatile than full generator definitions and tend to be more memory friendly than equivalent list comprehensions. Examples: ----- ----- **CHAPTER** ### TEN BRIEF TOUR OF THE STANDARD LIBRARY 10.1 Operating System Interface The os module provides dozens of func...
This will keep os.open() from shadowing the built-in open() function which operates much differently. The built-in dir() and help() functions are useful as interactive aids for working with large modules like ``` os: >>> import os >>> dir(os) <returns a list of all module functions> >>> help(os) <returns an extensive ...
These arguments are stored in the ``` sys module’s argv attribute as a list.
For instance the following output results from running python demo.py one two three at the command line: >>> import sys >>> print(sys.argv) ['demo.py', 'one', 'two', 'three'] ``` The getopt module processes sys.argv using the conventions of the Unix getopt() function.
More powerful and flexible command line processing is provided by the argparse module. ### 10.4 Error Output Redirection and Program Termination The sys module also has attributes for stdin, stdout, and stderr.
The latter is useful for emitting warnings and error messages to make them visible even when stdout has been redirected: ``` >>> sys.stderr.write('Warning, log file not found starting a new one\n') Warning, log file not found starting a new one ``` The most direct way to terminate a script is to use sys.exit(). ### 1...
For complex matching and manipulation, regular expressions offer succinct, optimized solutions: ``` >>> import re >>> re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest') ['foot', 'fell', 'fastest'] >>> re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat') 'cat in the hat' ``` When only simple capabilities are ...
Two of the simplest are urllib.request for retrieving data from URLs and smtplib for sending mail: ``` >>> from urllib.request import urlopen >>> with urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl') as response: ...
for line in response: ... line = line.decode('utf-8') # Decoding the binary data to text. ... if 'EST' in line or 'EDT' in line: # look for Eastern Time ... print(line) <BR>Nov.
25, 09:43:32 PM EST >>> import smtplib >>> server = smtplib.SMTP('localhost') >>> server.sendmail('soothsayer@example.org', 'jcaesar@example.org', ... """To: jcaesar@example.org ...
From: soothsayer@example.org ... ... Beware the Ides of March. ...
""") >>> server.quit() ``` (Note that the second example needs a mailserver running on localhost.) ### 10.8 Dates and Times The datetime module supplies classes for manipulating dates and times in both simple and complex ways. While date and time arithmetic is supported, the focus of the implementation is on efficie...
The module also supports objects that are timezone aware. ``` >>> # dates are easily constructed and formatted >>> from datetime import date >>> now = date.today() >>> now datetime.date(2003, 12, 2) >>> now.strftime("%m-%d-%y.
%d %b %Y is a %A on the %d day of %B.") '12-02-03.
02 Dec 2003 is a Tuesday on the 02 day of December.' >>> # dates support calendar arithmetic >>> birthday = date(1964, 7, 31) >>> age = now - birthday >>> age.days 14368 ### 10.9 Data Compression ``` Common data archiving and compression formats are directly supported by modules including: zlib, gzip, ``` bz2, lzma, ...
Python provides a measurement tool that answers those questions immediately. For example, it may be tempting to use the tuple packing and unpacking feature instead of the traditional approach to swapping arguments.
The timeit module quickly demonstrates a modest performance advantage: ``` >>> from timeit import Timer >>> Timer('t=a; a=b; b=t', 'a=1; b=2').timeit() 0.57535828626024577 >>> Timer('a,b = b,a', 'a=1; b=2').timeit() 0.54962537085770791 ``` In contrast to timeit’s fine level of granularity, the profile and pstats modul...
Test construction is as simple as cutting-and-pasting a typical call along with its results into the docstring.
This improves the documentation by providing the user with an example and it allows the doctest module to make sure the code remains true to the documentation: ``` def average(values): """Computes the arithmetic mean of a list of numbers. >>> print(average([20, 30, 70])) 40.0 """ return sum(values) / len(valu...
This is best seen through the sophisticated and robust capabilities of its larger packages.
For example: - The xmlrpc.client and xmlrpc.server modules make implementing remote procedure calls into an almost trivial task.
Despite the modules names, no direct knowledge or handling of XML is needed. [• The email package is a library for managing email messages, including MIME and other RFC 2822-](https://tools.ietf.org/html/rfc2822.html) based message documents.
Unlike smtplib and poplib which actually send and receive messages, the email package has a complete toolset for building or decoding complex message structures (including attachments) and for implementing internet encoding and header protocols. - The json package provides robust support for parsing this popular dat...
The csv module supports direct reading and writing of files in Comma-Separated Value format, commonly supported by databases and spreadsheets.
XML processing is supported by the xml.etree.ElementTree, ``` xml.dom and xml.sax packages.
Together, these modules and packages greatly simplify data inter ``` change between Python applications and other tools. ----- - The sqlite3 module is a wrapper for the SQLite database library, providing a persistent database that can be updated and accessed using slightly nonstandard SQL syntax. - Internationaliza...
These modules rarely occur in small scripts. ### 11.1 Output Formatting The reprlib module provides a version of repr() customized for abbreviated displays of large or deeply nested containers: ``` >>> import reprlib >>> reprlib.repr(set('supercalifragilisticexpialidocious')) "{'a', 'c', 'd', 'e', 'f', 'g', ...}" ``...
When the result is longer than one line, the “pretty printer” adds line breaks and indentation to more clearly reveal data structure: ``` >>> import pprint >>> t = [[[['black', 'cyan'], 'white', ['green', 'red']], [['magenta', ...
'yellow'], 'blue']]] ... >>> pprint.pprint(t, width=30) [[[['black', 'cyan'], 'white', ['green', 'red']], [['magenta', 'yellow'], 'blue']]] ``` The textwrap module formats paragraphs of text to fit a given screen width: ``` >>> import textwrap >>> doc = """The wrap() method is just like fill() except that it re...
a list of strings instead of one big string with newlines to separate ...
the wrapped lines.""" ... >>> print(textwrap.fill(doc, width=40)) The wrap() method is just like fill() except that it returns a list of strings instead of one big string with newlines to separate the wrapped lines. ``` The locale module accesses a database of culture specific data formats.
The grouping attribute of locale’s format function provides a direct way of formatting numbers with group separators: ----- ### 11.2 Templating The string module includes a versatile Template class with a simplified syntax suitable for editing by end-users.
This allows users to customize their applications without having to alter the application. The format uses placeholder names formed by $ with valid Python identifiers (alphanumeric characters and underscores).
Surrounding the placeholder with braces allows it to be followed by more alphanumeric letters with no intervening spaces.
Writing $$ creates a single escaped $: ``` >>> from string import Template >>> t = Template('${village}folk send $$10 to $cause.') >>> t.substitute(village='Nottingham', cause='the ditch fund') 'Nottinghamfolk send $10 to the ditch fund.' ``` The substitute() method raises a KeyError when a placeholder is not supplied...
For mail-merge style applications, user supplied data may be incomplete and the ``` safe_substitute() method may be more appropriate — it will leave placeholders unchanged if data is ``` missing: ``` >>> t = Template('Return the $item to $owner.') >>> d = dict(item='unladen swallow') >>> t.substitute(d) Traceback (mos...
For example, a batch renaming utility for a photo browser may elect to use percent signs for placeholders such as the current date, image sequence number, or file format: ``` >>> import time, os.path >>> photofiles = ['img_1074.jpg', 'img_1076.jpg', 'img_1077.jpg'] >>> class BatchRename(Template): ...
delimiter = '%' >>> fmt = input('Enter rename style (%d-date %n-seqnum %f-format): ') Enter rename style (%d-date %n-seqnum %f-format): Ashley_%n%f >>> t = BatchRename(fmt) >>> date = time.strftime('%d%b%y') >>> for i, filename in enumerate(photofiles): ...
base, ext = os.path.splitext(filename) ... newname = t.substitute(d=date, n=i, f=ext) ``` (continues on next page) ----- (continued from previous page) ``` ...
print('{0} --> {1}'.format(filename, newname)) img_1074.jpg --> Ashley_0.jpg img_1076.jpg --> Ashley_1.jpg img_1077.jpg --> Ashley_2.jpg ``` Another application for templating is separating program logic from the details of multiple output formats. This makes it possible to substitute custom templates for XML files, p...
The following example shows how to loop through header information in a ZIP file without using the zipfile module.
Pack codes "H" and "I" represent two and four byte unsigned numbers respectively. The "<" indicates that they are standard size and in little-endian byte order: ``` import struct with open('myfile.zip', 'rb') as f: data = f.read() start = 0 for i in range(3): # show the first 3 file headers start += 14 fields = s...
Threads can be used to improve the responsiveness of applications that accept user input while other tasks run in the background. A related use case is running I/O in parallel with computations in another thread. The following code shows how the high level threading module can run tasks in background while the main pr...
To that end, the threading module provides a number of synchronization primitives including locks, events, condition variables, and semaphores. While those tools are powerful, minor design errors can result in problems that are difficult to reproduce. So, the preferred approach to task coordination is to concentrate a...
Applications using ``` Queue objects for inter-thread communication and coordination are easier to design, more readable, and ``` more reliable. ### 11.5 Logging The logging module offers a full featured and flexible logging system.
At its simplest, log messages are sent to a file or to sys.stderr: ``` import logging logging.debug('Debugging information') logging.info('Informational message') logging.warning('Warning:config file %s not found', 'server.conf') logging.error('Error occurred') logging.critical('Critical error -- shutting down') ``` T...
Other output options include routing messages through email, datagrams, sockets, or to an HTTP Server.
New filters can select different routing based on message priority: DEBUG, INFO, WARNING, ERROR, and ``` CRITICAL. ``` The logging system can be configured directly from Python or can be loaded from a user editable configuration file for customized logging without altering the application. ----- ### 11.6 Weak Refer...
The memory is freed shortly after the last reference to it has been eliminated. This approach works fine for most applications but occasionally there is a need to track objects only as long as they are being used by something else.
Unfortunately, just tracking them creates a reference that makes them permanent.
The weakref module provides tools for tracking objects without creating a reference. When the object is no longer needed, it is automatically removed from a weakref table and a callback is triggered for weakref objects.
Typical applications include caching objects that are expensive to create: ``` >>> import weakref, gc >>> class A: ... def __init__(self, value): ... self.value = value ... def __repr__(self): ...
return str(self.value) ... >>> a = A(10) # create a reference >>> d = weakref.WeakValueDictionary() >>> d['primary'] = a # does not create a reference >>> d['primary'] # fetch the object if it is still alive 10 >>> del a # remove the one reference >>> gc.collect() # run garbage collection right away 0 >>> d['primary'] ...
However, sometimes there is a need for alternative implementations with different performance trade-offs. The array module provides an array() object that is like a list that stores only homogeneous data and stores it more compactly.
The following example shows an array of numbers stored as two byte unsigned binary numbers (typecode "H") rather than the usual 16 bytes per entry for regular lists of Python int objects: ``` >>> from array import array >>> a = array('H', [4000, 10, 700, 22222]) >>> sum(a) 26932 >>> a[1:3] array('H', [10, 700]) ``` Th...
These objects are well suited for implementing queues and breadth first tree searches: ----- In addition to alternative list implementations, the library also offers other tools such as the bisect module with functions for manipulating sorted lists: ``` >>> import bisect >>> scores = [(100, 'perl'), (200, 'tcl'), (4...
The lowest valued entry is always kept at position zero.
This is useful for applications which repeatedly access the smallest element but do not want to run a full list sort: ``` >>> from heapq import heapify, heappop, heappush >>> data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0] >>> heapify(data) # rearrange the list into heap order >>> heappush(data, -5) # add a new entry >>> [heappo...
Compared to the built-in float implementation of binary floating point, the class is especially helpful for - financial applications and other uses which require exact decimal representation, - control over precision, - control over rounding to meet legal or regulatory requirements, - tracking of significan...
The difference becomes significant if the results are rounded to the nearest cent: ----- The Decimal result keeps a trailing zero, automatically inferring four place significance from multiplicands with two place significance.
Decimal reproduces mathematics as done by hand and avoids issues that can arise when binary floating point cannot exactly represent decimal quantities. Exact representation enables the Decimal class to perform modulo calculations and equality tests that are unsuitable for binary floating point: ``` >>> Decimal('1.00')...
To resolve the earlier example of conflicting requirements, application A can have its own virtual environment with version 1.0 installed while application B has another virtual environment with version 2.0.
If application B requires a library be upgraded to version 3.0, this will not affect application A’s environment. ### 12.2 Creating Virtual Environments The module used to create and manage virtual environments is called venv.
venv will usually install the most recent version of Python that you have available.
If you have multiple versions of Python on your system, you can select a specific Python version by running python3 or whichever version you want. To create a virtual environment, decide upon a directory where you want to place it, and run the venv module as a script with the directory path: ``` python3 -m venv tutori...
If you use the csh or fish shells, there are alternate activate.csh and activate.fish scripts you should use instead.) Activating the virtual environment will change your shell’s prompt to show what virtual environment you’re using, and modify the environment so that running python will get you that particular version...
For example: ``` $ source ~/envs/tutorial-env/bin/activate (tutorial-env) $ python Python 3.5.1 (default, May 6 2016, 10:59:36) ... >>> import sys >>> sys.path ['', '/usr/local/lib/python35.zip', ..., '~/envs/tutorial-env/lib/python3.5/site-packages'] >>> ### 12.3 Managing Packages with pip ``` You can install, upgr...
By default pip will install [packages from the Python Package Index, <https://pypi.org>.
You can browse the Python Package Index](https://pypi.org) by going to it in your web browser, or you can use pip’s limited search feature: ``` (tutorial-env) $ pip search astronomy skyfield - Elegant astronomy for Python gary - Galactic astronomy and gravitational dynamics. novas - The United States Naval Observatory ...
(Consult the installing ``` index guide for complete documentation for pip.) You can install the latest version of a package by specifying a package’s name: ``` (tutorial-env) $ pip install novas Collecting novas Downloading novas-3.1.1.3.tar.gz (136kB) Installing collected packages: novas Running setup.py install f...
A common convention is to put this list in a requirements.txt file: (tutorial-env) $ pip freeze > requirements.txt (tutorial-env) $ cat requirements.txt novas==3.1.1.3 numpy==1.9.2 requests==2.7.0 ``` The requirements.txt can then be committed to version control and shipped as part of an application. Users can then in...
Consult the installing-index guide for complete documentation for pip.
When ``` you’ve written a package and want to make it available on the Python Package Index, consult the distributingindex guide. ----- **CHAPTER** ### THIRTEEN WHAT NOW? Reading this tutorial has probably reinforced your interest in using Python — you should be eager to apply Python to solving your real-world ...
Where should you go to learn more? This tutorial is part of Python’s documentation set.
Some other documents in the set are: - library-index: You should browse through this manual, which gives complete (though terse) reference material about types, functions, and the modules in the standard library.
The standard Python distribution includes a lot of additional code.
There are modules to read Unix mailboxes, retrieve documents via HTTP, generate random numbers, parse command-line options, write CGI programs, compress data, and many other tasks.
Skimming through the Library Reference will give you an idea of what’s available. - installing-index explains how to install additional modules written by other Python users. - reference-index: A detailed explanation of Python’s syntax and semantics.
It’s heavy reading, but is useful as a complete guide to the language itself. More Python resources: [• https://www.python.org: The major Python Web site.
It contains code, documentation, and pointers](https://www.python.org) to Python-related pages around the Web.
This Web site is mirrored in various places around the world, such as Europe, Japan, and Australia; a mirror may be faster than the main site, depending on your geographical location. [• https://docs.python.org: Fast access to Python’s documentation.](https://docs.python.org) [• https://pypi.org: The Python Package I...
Once you begin releasing code, you can register it here so that others can find it. [• https://code.activestate.com/recipes/langs/python/: The Python Cookbook is a sizable collection of](https://code.activestate.com/recipes/langs/python/) code examples, larger modules, and useful scripts.
Particularly notable contributions are collected in a book also titled Python Cookbook (O’Reilly & Associates, ISBN 0-596-00797-3.) [• http://www.pyvideo.org collects links to Python-related videos from conferences and user-group meet-](http://www.pyvideo.org) ings. [• https://scipy.org: The Scientific Python project...
The newsgroup and mailing list are gatewayed,](mailto:python-list@python.org) so messages posted to one will automatically be forwarded to the other.
There are hundreds of postings a day, asking (and answering) questions, suggesting new features, and announcing new modules.
Mailing list [archives are available at https://mail.python.org/pipermail/.](https://mail.python.org/pipermail/) ----- Before posting, be sure to check the list of Frequently Asked Questions (also called the FAQ).
The FAQ answers many of the questions that come up again and again, and may already contain the solution for your problem. ----- **CHAPTER** ### FOURTEEN INTERACTIVE INPUT EDITING AND HISTORY SUBSTITUTION Some versions of the Python interpreter support editing of the current input line and history substitution, ...
This is implemented using the GNU](https://tiswww.case.edu/php/chet/readline/rltop.html) [Readline library, which supports various styles of editing.
This library has its own documentation which we](https://tiswww.case.edu/php/chet/readline/rltop.html) won’t duplicate here. ### 14.1 Tab Completion and History Editing Completion of variable and module names is automatically enabled at interpreter startup so that the Tab key invokes the completion function; it looks...
For dotted expressions such as string.a, it will evaluate the expression up to the final '.' and then suggest completions from the attributes of the resulting object.
Note that this may execute application-defined code if an object with a __getattr__() method is part of the expression.
The default configuration also saves your history into a file named .python_history in your user directory.
The history will be available again during the next interactive interpreter session. ### 14.2 Alternatives to the Interactive Interpreter This facility is an enormous step forward compared to earlier versions of the interpreter; however, some wishes are left: It would be nice if the proper indentation were suggested ...
The completion mechanism might use the interpreter’s symbol table.
A command to check (or even suggest) matching parentheses, quotes, etc., would also be useful. [One alternative enhanced interactive interpreter that has been around for quite some time is IPython, which](https://ipython.org/) features tab completion, object exploration and advanced history management.
It can also be thoroughly customized and embedded into other applications.
Another similar enhanced interactive environment is [bpython.](https://www.bpython-interpreter.org/) ----- ----- **CHAPTER** ### FIFTEEN FLOATING POINT ARITHMETIC: ISSUES AND LIMITATIONS Floating-point numbers are represented in computer hardware as base 2 (binary) fractions.