Text of docs.python.org › 3.16 › tutorial › stdlib2.html as Styx crawled it on Oct 8, 2026. The page may have changed since. Only its words are kept, without pictures or layout, and only the first part of a long page.

Open the live page

11. Brief tour of the standard library — part II — Python 3.16.0a0 documentation

Navigation index modules | next | previous | Python » 3.16.0a0 Documentation » The Python Tutorial » 11. Brief tour of the standard library — part II | Theme | 11. Brief tour of the standard library — part II ¶ This second tour covers more advanced modules that support professional programming needs. 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', ...}" The pprint module offers more sophisticated control over printing both built-in and user defined objects in a way that is readable by the interpreter.

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 returns ... 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: >>> import locale >>> locale . setlocale ( locale . LC_ALL , 'English_United States.1252' ) 'English_United States.1252' >>> conv = locale . localeconv () # get a mapping of conventions >>> x = 1234567.8 >>> locale . format_string ( " %d " , x , grouping = True ) '1,234,567' >>> locale . format_string ( " %s%.*f " , ( conv [ 'currency_symbol' ], ... conv [ 'frac_digits' ], x ), grouping = True ) '$1,234,567.80' 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 in a dictionary or a keyword argument. 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 (most recent call last): ...

KeyError : 'owner' >>> t . safe_substitute ( d ) 'Return the unladen swallow to $owner.' Template subclasses can specify a custom delimiter. 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 ) ... 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, plain text reports, and HTML web reports. 11.3. Working with binary data record layouts ¶ The struct module provides pack() and unpack() functions for working with variable length binary record formats. 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 = struct . unpack ( '<IIIHH' , data [ start : start + 16 ]) crc32 , comp_size , uncomp_size , filenamesize , extra_size = fields start += 16 filename = data [ start : start + filenamesize ] start += filenamesize extra = data [ start : start + extra_size ] print ( filename , hex ( crc32 ), comp_size , uncomp_size ) start += extra_size + comp_size # skip to the next header 11.4.

Multi-threading ¶ Threading is a technique for decoupling tasks which are not sequentially dependent. 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 program continues to run: import threading , zipfile class AsyncZip ( threading .

Thread ): def __init__ ( self , infile , outfile ): super () . __init__ () self . infile = infile self . outfile = outfile def run ( self ): with zipfile . ZipFile ( self . outfile , 'w' , zipfile . ZIP_DEFLATED ) as f : f . write ( self . infile ) print ( 'Finished background zip of:' , self . infile ) background = AsyncZip ( 'mydata.txt' , 'myarchive.zip' ) background . start () print ( 'The main program continues to run in foreground.' ) background . join () # Wait for the background task to finish print ( 'Main program waited until background was done.' ) The principal challenge of multi-threaded applications is coordinating threads that share data or other resources.

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 all access to a resource in a single thread and then use the queue module to feed that thread with requests from other threads.

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' ) This produces the following output: WARNING:root:Warning:config file server.conf not found ERROR:root:Error occurred CRITICAL:root:Critical error -- shutting down By default, informational and debu

The rest of this page is on the live site.