Review of Python — Part 1D

Based mostly on the Tutorial, sections 6–8.

6 Modules

A module is a file containing Python definitions and statements.

Importing a module.

6.1 More on modules

Executable statements (not definitions) in a module are used to initialize the module. If the module is imported more than once, they are executed only the first time.

6.1.1 Module search paths

Where Python looks for modules.

Environment variable: PYTHONPATH

Python variable: sys.path is initialized from PYTHONPATH

6.1.2 Compiled Python files

These have extension .pyc or .pyo ("optimized"). They are bytecode files.

The interpreter creates them and reads them as needed.

They speed up loading a module, but not executing a program otherwise.

6.2 Standard modules

Are described in Python Library Reference.

6.3 The dir() function

Applied to a module, returns the list of names defined by the module:

import string
dir(string)

Applied with no arguments, returns the list of names the programmer has defined (interactively or in a script):

dir()

__builtins__ is the module containing builtin functions:

dir(__builtins__)

[Applied to a class, dir returns a list of methods or attributes of the class.]

[For more detail, use help(module), help(class), or help(function). Works similar to 'man'.]

6.4 Packages

Packages are collections of modules, hierarchically organized and named, e.g., foo1.foo2.foo3

The directory structure should mirror the package structure.

Skip:

6.4.1 Importing * from a package
6.4.2 Intra-package references
6.4.3 Packages in multiple directories

7 Input and Output

7.1 Formatting

*** MAY NEED REVISION ***

To be formatted, an object must be converted to a string.

str(obj) → human-readable string representation of obj

repr(obj) → string representation of obj which the interpreter can read to recreate the object

The format operator %

"%d %s %f" % (12, "abc", 1.2)
"%10d" % (12)
"%8.5f" % (1.2)

String methods

s.rjust(width)
s.ljust(width)
s.center(width)

7.2 File I/O

f = open(path, [mode])

mode values:

Windows and (old?) Mac need an additional 'b' for binary mode: 'rb', 'wb', 'r+b', because of the way they handle end of lines in text files. [On Unix, the 'b' isn't needed; the o.s. makes no distinction between binary and text files.]

[You should also close the file:]

f.close()

7.2.1 File methods

Assume f is an open file. These are some of f's methods:

f.read() → string containing all the bytes of f
returns "" at EOF.
f.readline() → one line including its \n if any
Returns "\n" for an "empty" line.
Returns "" at EOF.
f.readlines() → list of lines (as in readline) of the file.

For more efficient use of memory, instead of readlines use

for line in f: ...

f.write(s) writes the string s to file f. Non-string objects must be explicitly converted to string before writing, e.g., using str or repr.

[Skip random access:]

f.tell()
f.seek(...)

7.2.2 The pickle module

*** NEEDS REVISION ***

Pickling, unpickling = converting almost any object to string and back.

Useful for persistent storage (in a file) or network transmission of objects.

# pickling and storing the object:
import pickle
x = ...
f = open(...)
pickle.dump(x, f)

# unpickling:
import pickle
f = open(...)
x = pickle.load(f)

See Python Library Reference for other pickle options.

8 Errors and Exceptions

8.1 Syntax errors

8.2 Exceptions

The Python Library Reference lists the builtin exceptions.

8.3 Handling exceptions

Use try/except:

try:
  ... # some statements which may raise an exception
except ValueError: # exception type
  ... # what to do with the exception

To ignore the exception, use the 'pass' statement in the except clause.

Longer form: e1 is the instance of E1, e2 of E2:

try:
  ...
except E1 as e1: # in Python 2: except E1, e1:
  ...
except E2 as e2:
  ...
else:
  ... # what to do if no exceptions occurred

8.4 Raising exceptions

raise ValueError()

8.5 User-defined exceptions

Define a subclass of Exception. You can give it methods like __init__ and __str__.

8.6 Clean-up actions

Use the finally clause for cleanup after normal execution or after handling any exceptions. It is always executed before leaving the try statement, whether normally or not.

try:
  ...
except ...:
  ...
finally:
  ...

Suggested Exercises

  1. Write Python format expressions to:
    1. Format an integer in a field of width 12, e.g., 1600 as "      1600" (6 spaces before the "1").
    2. Format a floating point number with 6 digits of precision to the right of the decimal point, e.g., 1.5 as 1.500000
    3. Format three strings separated by "+" signs, e.g., "cat", "chases", "dog" as "cat+chases+dog".
  2. Write a Python function that writes the formatted data from the previous problem to a 3-line text file.
  3. Write a Python function to read the file from the previous exercise, and print the sum of the two numbers plus the length of the third line, not including the line-ending character(s) such as "\r" and "\n". E.g., 1600 + 1.5 + length of "cat+chases+dog" = 1615.5. Include code to handle errors graciously, including "file not found" errors, non-numerical data on the first two lines, and premature end of file.

→ Solutions