You are here: Home Dive Into Python 3

Difficulty level: ♦♦♢♢♢

Comprehensions

Our imagination is stretched to the utmost, not, as in fiction, to imagine things which are not really there, but just to comprehend those things which are.
Richard Feynman

 

Diving In

This chapter will teach you about list comprehensions, dictionary comprehensions, and set comprehensions: three related concepts centered around one very powerful technique. But first, I want to take a little detour into two modules that will help you navigate your local file system.

Working With Files And Directories

Python 3 comes with a module called os, which stands for “operating system.” The os module contains a plethora of functions to get information on — and in some cases, to manipulate — local directories, files, processes, and environment variables. Python does its best to offer a unified API across all supported operating systems so your programs can run on any computer with as little platform-specific code as possible.

The Current Working Directory

When you’re just getting started with Python, you’re going to spend a lot of time in the Python Shell. Throughout this book, you will see examples that go like this:

  1. Import one of the modules in the examples folder
  2. Call a function in that module
  3. Explain the result

If you don’t know about the current working directory, step 1 will probably fail with an ImportError. Why? Because Python will look for the example module in the import search path, but it won’t find it because the examples folder isn’t one of the directories in the search path. To get past this, you can do one of two things:

  1. Add the examples folder to the import search path
  2. Change the current working directory to the examples folder

The current working directory is an invisible property that Python holds in memory at all times. There is always a current working directory, whether you’re in the Python Shell, running your own Python script from the command line, or running a Python CGI script on a web server somewhere.

The os module contains two functions to deal with the current working directory.

>>> import os                                            
>>> print(os.getcwd())                                   
C:\Python31
>>> os.chdir('/Users/pilgrim/diveintopython3/examples')  
>>> print(os.getcwd())                                   
C:\Users\pilgrim\diveintopython3\examples
  1. The os module comes with Python; you can import it anytime, anywhere.
  2. Use the os.getcwd() function to get the current working directory. When you run the graphical Python Shell, the current working directory starts as the directory where the Python Shell executable is. On Windows, this depends on where you installed Python; the default directory is c:\Python31. If you run the Python Shell from the command line, the current working directory starts as the directory you were in when you ran python3.
  3. Use the os.chdir() function to change the current working directory.
  4. When I called the os.chdir() function, I used a Linux-style pathname (forward slashes, no drive letter) even though I’m on Windows. This is one of the places where Python tries to paper over the differences between operating systems.

Working With Filenames and Directory Names

While we’re on the subject of directories, I want to point out the os.path submodule. os.path contains functions for manipulating filenames and directory names.

>>> import os
>>> print(os.path.join('/Users/pilgrim/diveintopython3/examples/', 'humansize.py'))              
/Users/pilgrim/diveintopython3/examples/humansize.py
>>> print(os.path.join('/Users/pilgrim/diveintopython3/examples', 'humansize.py'))               
/Users/pilgrim/diveintopython3/examples\humansize.py
>>> print(os.path.expanduser('~'))                                                               
c:\Users\pilgrim
>>> print(os.path.join(os.path.expanduser('~'), 'diveintopython3', 'examples', 'humansize.py'))  
c:\Users\pilgrim\diveintopython3\examples\humansize.py
  1. The os.path.join() function constructs a pathname out of one or more partial pathnames. In this case, it simply concatenates strings.
  2. In this slightly less trivial case, join will add an extra backslash to the pathname before joining it to the filename. I was overjoyed when I discovered this, since addSlashIfNecessary() is one of the stupid little functions I always need to write when building up my toolbox in a new language. Do not write this stupid little function in Python; smart people have already taken care of it for you.
  3. The os.path.expanduser() function will expand a pathname that uses ~ to represent the current user’s home directory. This works on any platform where users have a home directory, including Linux, Mac OS X, and Windows.
  4. Combining these techniques, you can easily construct pathnames for directories and files under the user’s home directory.

os.path also contains functions to split full pathnames, directory names, and filenames into their constituent parts.

>>> pathname = '/Users/pilgrim/diveintopython3/examples/humansize.py'
>>> os.path.split(pathname)                                        
('/Users/pilgrim/diveintopython3/examples', 'humansize.py')
>>> (dirname, filename) = os.path.split(pathname)                  
>>> dirname                                                        
'/Users/pilgrim/diveintopython3/examples'
>>> filename                                                       
'humansize.py'
>>> (shortname, extension) = os.path.splitext(filename)            
>>> shortname
'humansize'
>>> extension
'.py'
  1. The split function splits a full pathname and returns a tuple containing the path and filename. Remember when I said you could use multi-variable assignment to return multiple values from a function? The os.path.split() function does exactly that.
  2. You assign the return value of the split function into a tuple of two variables. Each variable receives the value of the corresponding element of the returned tuple.
  3. The first variable, dirname, receives the value of the first element of the tuple returned from the os.path.split() function, the file path.
  4. The second variable, filename, receives the value of the second element of the tuple returned from the os.path.split() function, the filename.
  5. os.path also contains the os.path.splitext() function, which splits a filename and returns a tuple containing the filename and the file extension. You use the same technique to assign each of them to separate variables.

Listing Directories

The glob module is another tool in the Python standard library. It’s an easy way to get the contents of a directory programmatically, and it uses the sort of wildcards that you may already be familiar with from working on the command line.

>>> os.chdir('/Users/pilgrim/diveintopython3/')
>>> import glob
>>> glob.glob('examples/*.xml')                  
['examples\\feed-broken.xml',
 'examples\\feed-ns0.xml',
 'examples\\feed.xml']
>>> os.chdir('examples/')                        
>>> glob.glob('*test*.py')                       
['alphameticstest.py',
 'pluraltest1.py',
 'pluraltest2.py',
 'pluraltest3.py',
 'pluraltest4.py',
 'pluraltest5.py',
 'pluraltest6.py',
 'romantest1.py',
 'romantest10.py',
 'romantest2.py',
 'romantest3.py',
 'romantest4.py',
 'romantest5.py',
 'romantest6.py',
 'romantest7.py',
 'romantest8.py',
 'romantest9.py']
  1. The glob module takes a wildcard and returns the path of all files and directories matching the wildcard. In this example, the wildcard is a directory path plus “*.xml”, which will match all .xml files in the examples subdirectory.
  2. Now change the current working directory to the examples subdirectory. The os.chdir() function can take relative pathnames.
  3. You can include multiple wildcards in your glob pattern. This example finds all the files in the current working directory that end in a .py extension and contain the word test anywhere in their filename.

Getting File Metadata

Every modern file system stores metadata about each file: creation date, last-modified date, file size, and so on. Python provides a single API to access this metadata. You don’t need to open the file; all you need is the filename.

>>> import os
>>> print(os.getcwd())                 
c:\Users\pilgrim\diveintopython3\examples
>>> metadata = os.stat('feed.xml')     
>>> metadata.st_mtime
1247520344.9537716
>>> import time                        
>>> time.localtime(metadata.st_mtime)  
time.struct_time(tm_year=2009, tm_mon=7, tm_mday=13, tm_hour=17,
  tm_min=25, tm_sec=44, tm_wday=0, tm_yday=194, tm_isdst=1)
  1. FIXME
  2. FIXME
  3. FIXME
  4. FIXME
# continued from the previous example
>>> metadata.st_size                              
3070
>>> import humansize
>>> humansize.approximate_size(metadata.st_size)  
'3.0 KiB'
  1. FIXME
  2. FIXME

Constructing Absolute Pathnames

In the previous example, the glob.glob() function returned a list of relative pathnames. The first example had pathnames like 'examples\feed.xml', and the second example had even shorter relative pathnames like 'romantest1.py'. As long as you stay in the same current working directory, these relative pathnames will work for opening files or getting file metadata. But if you want to construct an absolute pathname — i.e. one that includes all the directory names back to the root directory or drive letter — then you’ll need the os.path.abspath() function.

>>> import os
>>> print(os.getcwd())
c:\Users\pilgrim\diveintopython3\examples
>>> print(os.path.abspath('feed.xml'))
c:\Users\pilgrim\diveintopython3\examples\feed.xml

List Comprehensions

A list comprehension provides a compact way of mapping a list into another list by applying a function to each of the elements of the list.

>>> a_list = [1, 9, 8, 4]
>>> [elem * 2 for elem in a_list]          
[2, 18, 16, 8]
>>> a_list                                 
[1, 9, 8, 4]
>>> a_list = [elem * 2 for elem in a_list] 
>>> a_list
[2, 18, 16, 8]
  1. To make sense of this, look at it from right to left. a_list is the list you’re mapping. The Python interpreter loops through a_list one element at a time, temporarily assigning the value of each element to the variable elem. Python then applies the function elem * 2 and appends that result to the returned list.
  2. A list comprehension creates a new list; it does not change the original list.
  3. It is safe to assign the result of a list comprehension to the variable that you’re mapping. Python constructs the new list in memory, and when the list comprehension is complete, it assigns the result to the original variable.

FIXME

>>> glob.glob('*.xml')
['feed-broken.xml', 'feed-ns0.xml', 'feed.xml']
>>> [os.path.abspath(filename) for filename in glob.glob('*.xml')]
['c:\\Users\\pilgrim\\diveintopython3\\examples\\feed-broken.xml',
 'c:\\Users\\pilgrim\\diveintopython3\\examples\\feed-ns0.xml',
 'c:\\Users\\pilgrim\\diveintopython3\\examples\\feed.xml']
>>> print("\n".join(["{0:>8} {1}".format(humansize.approximate_size(os.stat(f).st_size, False), os.path.abspath(f)) for f in glob.glob('*.py')]))
  2.5 KB c:\Users\pilgrim\diveintopython3\examples\alphametics.py
  2.5 KB c:\Users\pilgrim\diveintopython3\examples\alphameticstest.py
  1.5 KB c:\Users\pilgrim\diveintopython3\examples\fibonacci.py
  1.8 KB c:\Users\pilgrim\diveintopython3\examples\fibonacci2.py
  2.5 KB c:\Users\pilgrim\diveintopython3\examples\humansize.py
  0.2 KB c:\Users\pilgrim\diveintopython3\examples\oneline.py
  1.9 KB c:\Users\pilgrim\diveintopython3\examples\plural1.py
  2.3 KB c:\Users\pilgrim\diveintopython3\examples\plural2.py
  2.3 KB c:\Users\pilgrim\diveintopython3\examples\plural3.py
  2.3 KB c:\Users\pilgrim\diveintopython3\examples\plural4.py
  2.4 KB c:\Users\pilgrim\diveintopython3\examples\plural5.py
  2.8 KB c:\Users\pilgrim\diveintopython3\examples\plural6.py
  3.0 KB c:\Users\pilgrim\diveintopython3\examples\pluraltest1.py
  3.0 KB c:\Users\pilgrim\diveintopython3\examples\pluraltest2.py
  3.0 KB c:\Users\pilgrim\diveintopython3\examples\pluraltest3.py
  3.0 KB c:\Users\pilgrim\diveintopython3\examples\pluraltest4.py
  3.0 KB c:\Users\pilgrim\diveintopython3\examples\pluraltest5.py
  6.1 KB c:\Users\pilgrim\diveintopython3\examples\pluraltest6.py
  0.5 KB c:\Users\pilgrim\diveintopython3\examples\regression.py
  2.2 KB c:\Users\pilgrim\diveintopython3\examples\roman1.py
  3.4 KB c:\Users\pilgrim\diveintopython3\examples\roman10.py
  2.3 KB c:\Users\pilgrim\diveintopython3\examples\roman2.py
  2.3 KB c:\Users\pilgrim\diveintopython3\examples\roman3.py
  2.5 KB c:\Users\pilgrim\diveintopython3\examples\roman4.py
  2.7 KB c:\Users\pilgrim\diveintopython3\examples\roman5.py
  3.6 KB c:\Users\pilgrim\diveintopython3\examples\roman6.py
  3.7 KB c:\Users\pilgrim\diveintopython3\examples\roman7.py
  3.7 KB c:\Users\pilgrim\diveintopython3\examples\roman8.py
  3.7 KB c:\Users\pilgrim\diveintopython3\examples\roman9.py
  4.0 KB c:\Users\pilgrim\diveintopython3\examples\romantest1.py
  6.7 KB c:\Users\pilgrim\diveintopython3\examples\romantest10.py
  4.2 KB c:\Users\pilgrim\diveintopython3\examples\romantest2.py
  4.5 KB c:\Users\pilgrim\diveintopython3\examples\romantest3.py
  4.7 KB c:\Users\pilgrim\diveintopython3\examples\romantest4.py
  5.3 KB c:\Users\pilgrim\diveintopython3\examples\romantest5.py
  6.1 KB c:\Users\pilgrim\diveintopython3\examples\romantest6.py
  6.3 KB c:\Users\pilgrim\diveintopython3\examples\romantest7.py
  6.5 KB c:\Users\pilgrim\diveintopython3\examples\romantest8.py
  6.6 KB c:\Users\pilgrim\diveintopython3\examples\romantest9.py
  0.4 KB c:\Users\pilgrim\diveintopython3\examples\stdout.py

Set Comprehensions

FIXME

Dictionary Comprehensions

FIXME

Further Reading

© 2001–9 Mark Pilgrim