diff --git a/comprehensions.html b/comprehensions.html index 6d19fbe..79db3bf 100644 --- a/comprehensions.html +++ b/comprehensions.html @@ -16,13 +16,13 @@ body{counter-reset:h1 3}

Difficulty level: ♦♦♢♢♢

Comprehensions

-

FIXME
— FIXME +

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. -

The os module

+

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. @@ -61,7 +61,7 @@ body{counter-reset:h1 3}

  • 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. -

    The os.path module

    +

    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. @@ -106,7 +106,7 @@ body{counter-reset:h1 3}

  • 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. -

    The glob module

    +

    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. @@ -142,70 +142,82 @@ body{counter-reset:h1 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. -

    Now you’re ready to learn about comprehensions. +

    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

    -

    One of the most powerful features of Python is the list comprehension, which provides a compact way of mapping a list into another list by applying a function to each - of the elements of the list. - -

    >>> li = [1, 9, 8, 4]
    ->>> [elem * 2 for elem in li]      
    -[2, 18, 16, 8]
    ->>> li         
    -[1, 9, 8, 4]
    ->>> li = [elem * 2 for elem in li] 
    ->>> li
    -[2, 18, 16, 8]
    -
      -
    1. To make sense of this, look at it from right to left. li is the list you're mapping. Python loops through li 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. Note that list comprehensions do 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 variable. -
    - -

    FIXME Here are the list comprehensions in the buildConnectionString function that you declared in Chapter 2: - -

    ["%s=%s" % (k, v) for k, v in params.items()]
    - -

    First, notice that you're calling the items function of the params dictionary. This function returns a list of tuples of all the data in the dictionary. +

    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.

    ->>> params = {"server":"mpilgrim", "database":"master", "uid":"sa", "pwd":"secret"}
    ->>> params.keys()   
    -['server', 'uid', 'database', 'pwd']
    ->>> params.values() 
    -['mpilgrim', 'sa', 'master', 'secret']
    ->>> params.items()  
    -[('server', 'mpilgrim'), ('uid', 'sa'), ('database', 'master'), ('pwd', 'secret')]
    +>>> 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. The keys method of a dictionary returns a list of all the keys. The list is not in the order in which the dictionary was defined - (remember that elements in a dictionary are unordered), but it is a list. -
    2. The values method returns a list of all the values. The list is in the same order as the list returned by keys, so params.values()[n] == params[params.keys()[n]] for all values of n. -
    3. The items method returns a list of tuples of the form (key, value). The list contains all the data in the dictionary. -
    - -

    Now let's see what buildConnectionString does. It takes a list, params.items(), and maps it to a new list by applying string formatting to each element. The new list will have the same number of elements -as params.items(), but each element in the new list will be a string that contains both a key and its associated value from the params dictionary. - -

    ->>> params = {"server":"mpilgrim", "database":"master", "uid":"sa", "pwd":"secret"}
    ->>> params.items()
    -[('server', 'mpilgrim'), ('uid', 'sa'), ('database', 'master'), ('pwd', 'secret')]
    ->>> [k for k, v in params.items()]                
    -['server', 'uid', 'database', 'pwd']
    ->>> [v for k, v in params.items()]                
    -['mpilgrim', 'sa', 'master', 'secret']
    ->>> ["%s=%s" % (k, v) for k, v in params.items()] 
    -['server=mpilgrim', 'uid=sa', 'database=master', 'pwd=secret']
    -
      -
    1. Note that you're using two variables to iterate through the params.items() list. This is another use of multi-variable assignment. The first element of params.items() is ('server', 'mpilgrim'), so in the first iteration of the list comprehension, k will get 'server' and v will get 'mpilgrim'. In this case, you're ignoring the value of v and only including the value of k in the returned list, so this list comprehension ends up being equivalent to params.keys(). -
    2. Here you're doing the same thing, but ignoring the value of k, so this list comprehension ends up being equivalent to params.values(). -
    3. Combining the previous two examples with some simple string formatting, you get a list of strings that include both the key and value of each element of the dictionary. This looks suspiciously - like the output of the program. All that remains is to join the elements in this list into a single string. +
    4. 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. +
    5. A list comprehension creates a new list; it does not change the original list. +
    6. 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