Based mostly on the Tutorial, sections 6–8.
A module is a file containing Python definitions and statements.
Importing a module.
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.
Where Python looks for modules.
Environment variable: PYTHONPATH
Python variable: sys.path
is initialized from PYTHONPATH
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.
Are described in Python Library Reference.
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'.]
Packages are collections of modules, hierarchically organized
and named, e.g.,
foo1.foo2.foo3
The directory structure should mirror the package structure.
Skip:
*** 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
"%d %s %f" % (12, "abc", 1.2) "%10d" % (12) "%8.5f" % (1.2)
s.rjust(width) s.ljust(width) s.center(width)
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()
Assume f is an open file. These are some of f's methods:
f.read() → string containing all the bytes of f
f.readline() → one line including its \n if any
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(...)
*** 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.
The Python Library Reference lists the builtin 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
raise ValueError()
Define a subclass of Exception. You can give it methods like
__init__ and __str__.
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: ...