Style chooser: Modern, Modern B&W, Classic, High contrast or Printing

Contents

Front matter

Version 2.4
The latest version is to be found here.
Please report errors, inaccuracies and suggestions to Richard Gruet (pqr at rgruet.net).

Last modified on Oct 05, 2005
17 Feb 2005,
upgraded by Richard Gruet for Python 2.4
03 Oct 2003,
upgraded by Richard Gruet for Python 2.3
11 May 2003, rev 4
upgraded by Richard Gruet for Python 2.2 (restyled by Andrei)
7 Aug 2001
upgraded by Simon Brunning for Python 2.1
16 May 2001
upgraded by Richard Gruet and Simon Brunning for Python 2.0
18 Jun 2000
upgraded by Richard Gruet for Python 1.5.2
30 Oct 1995
created by Chris Hoffmann for Python 1.3
Color coding:
Features added in 2.4 since 2.3.
Features added in 2.3 since 2.2.
Features added in 2.2 since 2.1.
Originally based on:
Useful links :
Tip: From within the Python interpreter, type help, help(object) or help("name") to get help.

起動オプション

python[w] [-dEhimOQStuUvVWxX?] [-c command | scriptFile | - ] [args]
    (pythonw はターミナル/コンソールを開きません; python だと開きます)
Invocation Options
Option Effect
-d デバッグ情報を出力します (もしくは PYTHONDEBUG=x)
-E 環境変数を無視します (例えば PYTHONPATH)
-h ヘルプメッセージを出力して終了します (formerly -?)
-i Inspect interactively after running script (also PYTHONINSPECT=x) and force prompts, even if stdin appears not to be a terminal.
-m module モジュールを sys.path から探索し、スクリプトとして実行します。
-O 生成されたバイトコードを最適化します (also PYTHONOPTIMIZE=x). Asserts は抑制されます。
-OO -Oによる最適化に加えて、doc-strings を削除します。
-Q arg Division options: -Qold (default), -Qwarn, -Qwarnall, -Qnew
-S 初期化の際に、import site を評価しません。
-t Issue warnings about inconsistent tab usage (-tt: issue errors).
-u binary stdout and stderr をバッファーしない (also PYTHONUNBUFFERED=x).
-U 強制的にすべての文字列リテラルをUnicodeリテラルとしてPythonに解釈させる。
-v 詳細な情報出力 (trace import statements) (also PYTHONVERBOSE=x).
-V Pythonのバージョン情報を出力して終了。
-W arg 警告の制御 (arg is action:message:category:module:lineno)
-x ソースの最初の行をスキップする。 #!cmd の非unix形式を許可する。
-X Disable class based built-in exceptions (for backward compatibility management of exceptions)
-c command Specify the command to execute (see next section). This terminates the option list (following options are passed as arguments to the command).
scriptFile 実行するPythonファイルの名前を指定する。 Read from stdin.
- プログラムをstdinから読み込む。 (標準では、ttyの時にインタラクティブモードになる).
args スクリプトもしくはコマンドに渡される引数 (sys.argv[1:] に格納される)
  スクリプトファイル もしくは コマンド が存在しなかった場合、Pythonはインタラクティブモードに入る。
  • 標準でディストリビューションに付属している IDE: IDLE (tkinterベース, portable), Pythonwin (on Windows).  その他のフリーな IDE: IPython (enhanced interactive Python shell), ERIC, SPE, BOA constructor.
  • 典型的な python module header :
  • #!/usr/bin/env python
    # -*- coding: latin1 -*-
    Since 2.3 からPythonソースファイルのエンコーディングは先頭2行のうちいづれかに必ず宣言することになっています (宣言されていない場合、 7 bits Ascii が標準として選択されます)。 [PEP-0263], エンコード宣言のフォーマットは以下の形式:
    # -*- coding: encoding -*-
    標準の encodings は ここ に定義されています, 例えば、 ISO-8859-1 (aka latin1), iso-8859-15 (latin9), UTF-8... すべてのエンコーディングがサポートされているわけではありません, 具体的には UTF-16 がサポートされていません。
  • Site カスタマイズ: ファイル sitecustomize.py がPython path に存在する場合、Pythonによって自動的にロードされます (ideally located in ${PYTHONHOME}/lib/site-packages/).
  • Tip: Windows上でPythonスクリプトを実行した場合,
    <pythonHome>\python myScript.py args ... can be reduced to :
    myScript.py args ... if <pythonHome> is in the PATH envt variable, and further reduced to :
    myScript args ... provided that .py;.pyw;.pyc;.pyo is added to the PATHEXT envt variable.

環境変数

Environment variables
Variable Effect
PYTHONHOME Alternate prefix directory (or prefix;exec_prefix). デフォルトのモジュールサーチパスは prefix/lib を使用します。
PYTHONPATH モジュールファイルのためのデフォルトの探索パスを列挙する。 フォーマットはシェルの $PATH: と同じ。1つまたはそれより多くのディレクトリパス名を区切るには、':' か ';' を使用する。(セミ-)コロンの前後をスペースで囲んではダメですよ!
Windows環境上では、最初に レジストリキー HKEY_LOCAL_MACHINE\Software\Python\PythonCore\x.y\PythonPath (default value)が探索される。 You may also define a key named after your application with a default string value giving the root directory path of your app.
Alternatively, you can create a text file in the Python home directory with a .pth extension, containing the path (one per line).
PYTHONSTARTUP この環境変数が、読み込み可能なファイルの名前であった場合、インタラクティブモードの最初のプロンプトが表示される前に当該ファイルの中のPythonコマンド列が実行される。(no default).
PYTHONDEBUG 空でない場合, オプション -d  と同じ
PYTHONINSPECT 空でない場合, オプション -i と同じ
PYTHONOPTIMIZE 空でない場合, オプション -O と同じ
PYTHONUNBUFFERED 空でない場合, オプション -u と同じ
PYTHONVERBOSE 空でない場合, オプション -v と同じ
PYTHONCASEOK 空でない場合, importするファイル名/モジュール名の大小文字の違いを無視する。

Notable lexical entities

Keywords

        and       del       for       is        raise
assert elif from lambda return
break else global not try
class except if or while
continue exec import pass yield
def finally in print
  • (キーワードのリストは std module の中に存在します: keyword)
  • 規則違反となるトークン (文字列にのみ許される): $ ? (2.4より前のバージョンでは @ も含む)
  • ステートメントはすべて一行以内に記述しなければいけない。ステートメントを複数行に分けて記述する場合、C言語のプリプロセッサのように、"\" を使用する。
    例外: 次の記号 (), [], or {} のペアで囲まれるか、もしくは三連クオートで囲まれている場合は、常に複数行に分けて記述可能である。
  • ステートメントをセミコロン(";")で区切ると、1行内に複数ステートメントを記述できる。
  • "#"から行末までは、コメントとして解釈される。

Identifiers

(letter | "_") (letter | digit | "_")*
  • Pythonではキーワード,アトリビュート,その他が大文字小文字を区別して認識される。
  • 特別な形式: _ident ( 'from module import *' とした場合インポートされない。); __ident__ (システム定義された名前); __ident (クラス・プライベート化のためのネーム・マングリング(名前ぶった切り) class-private name mangling).

String literals

2種類: str (8 bits/文字 のプレーンで古い形式の文字列) と unicode (16 bits/文字 のUCS2を採用した文字列).

Literal
"a string enclosed by double quotes"    文字列はダブルクオートで囲まれます
'another string delimited by single quotes and with a " inside'    シングルクオートで囲むと " を文字列中で使えます
'''a string containing embedded newlines and quote (') marks, can be delimited with triple quotes.'''    3連クオートで囲むと、改行とクオート(')記号を含む文字列が記述できます
""" may also use 3- double quotes as delimiters """   文字列区切りには 3連ダブルクオート も使用できます
u'a unicode string'    unicode文字列
U"Another unicode string"    unicode文字列
r'a raw string where \ are kept (literalized): handy for regular expressions and windows paths!'    raw文字列では \ が保持(literalized)されます: 正規表現やwindowsのpathの記述に便利です!
R"another raw string"   -- raw strings cannot end with a \    -- raw文字列の末尾には \ を使用できません
ur'a unicode raw string'    raw形式のunicode文字列
UR"another raw unicode"    raw形式のunicode文字列
  • 文字列が次行に続く場合は、行末に \ を置く。
  • 隣接する文字列は結合されます。例えば 'Monty ' 'Python''Monty Python' と同じです。
  • u'hello' + ' world'  --> u'hello world'   (片方がunicode文字列の場合、強制的にunicode文字列にされる)

String Literal Escapes
Escape Meaning
\newline 無視 (escape newline)
\\ バックスラッシュ (\)
\e エスケープ文字 (ESC)
\v 垂直タブ (VT)
\' シングルクオート (')
\f フォームフィード (FF)
\ooo 8進数oooで表現された文字
\" ダブルクオート (")
\n ラインフィード・行頭 (LF)
\a ベル (BEL)
\r キャリッジリターン・行送り (CR)
\xhh 16進数hhで表現された文字
\b バックスペース (BS)
\t 水平タブ (TAB)
\uxxxx 16bitの値xxxxで表現された文字 (unicode only)
\Uxxxxxxxx 32bitの値xxxxxxxxで表現された文字 (unicode only)
\N{name} Unicodeデータベースで名前が定義されている文字 (unicode only), 例 u'\N{Greek Small Letter Pi}' <=> u'\u03c0'.
(反対に, unicodedata モジュールから名前を引く場合, unicodedata.name(u'\u03c0') == 'GREEK SMALL LETTER PI')
\AnyOtherChar そのまま。バックスラッシュがエスケープされる。 例 str('\z') == '\\z'
  • NUL byte (\000) は 文字列の終端記号ではありません; したがって NUL を文字列中に埋め込むことができます。
  • Strings (と tuples) は 不変です: これらを書き換えることはできません。

Boolean constants (2.2.1 以降)

  • True
  • False

バージョン 2.2.1 では, True と False は 整数 1 と 0 です. バージョン 2.3 からは、 新しい型 bool が使用されます。

Numbers

  • Decimal integer (10進数 整数): 1234, 1234567890546378940L (もしくは l)
  • Octal integer (8進数): 0177, 0177777777777777777L (0 から始まる)
  • Hex integer (16進数): 0xFF, 0XFFFFffffFFFFFFFFFFL (0x もしくは 0X から始まる)
  • Long integer (無限精度整数): 1234567890123456L (Ll で終わる) もしくは long(1234) と記述する
  • Float (倍精度小数点数): 3.14e-10, .001, 10., 1E3
  • Complex (複素数): 1J, 2+3J, 4+5j (Jj で終わる, (float)の実数部と虚数部はプラス記号(+)で区切る)

Integers と long integers は リリース2.2から 統合 されています (ゆえに、もはや L を末尾に追加する必要はありません)

Sequences

  • Strings (types str and unicode) の長さが 0, 1, 2 (上記参照) となる例:
      '', '1', "12", 'hello\n'
  • Tuples (type tuple) の長さが 0, 1, 2, となる例:
      () (1,) (1,2) # len > 0 の場合 括弧はあってもなくてもよい 
  • Lists (type list) の長さが 0, 1, 2, となる例:
      [] [1] [1,2]
  • 要素のインデックスは 0 から始まる。 インデックスに負の数を使用すると(通常は)シーケンスの末尾からのカウントを表す。
  • シーケンスのスライス表現 [ここから開始 : このインデックスより前で終端 [ : step]]. 通常は開始位置が0, 終端位置がlen(sequence), step が 1.
      a = (0,1,2,3,4,5,6,7)
    a[3] == 3
    a[-1] == 7
    a[2:4] == (2, 3)
    a[1:] == (1, 2, 3, 4, 5, 6, 7)
    a[:3] == (0, 1, 2)
    a[:] == (0,1,2,3,4,5,6,7) # シーケンスのコピーを生成.
    a[::2] == (0, 2, 4, 6) # 偶数のみ.
    a[::-1] = (7, 6, 5, 4, 3 , 2, 1, 0) # 順序を反転.

Dictionaries (Mappings)

Dictionaries (type dict) の長さが 0, 1, 2, となる例: {} {1 : 'first'} {1 : 'first', 'two': 2, key:value}
Keys は hashable type でなくてはいけない; Values はどんなtypeでもよい.

Operators and their evaluation order

オペレータ と それらを評価する際の優先順位
優先順位 高 Operator Comment
  , [...] {...} `...` タプル, リスト & 辞書(dict) の生成; 文字列変換.
s[i] s[i:j] s.attr f(...) インデクシング & スライシング; アトリビュート, 関数呼出
+x, -x, ~x 単項演算子
x**y 乗算 xのy乗
x*y x/y x%y 積、商、モジュロ(余)
x+y x-y 加算、 減算
x<<y   x>>y ビットシフト
x&y ビット単位でAND
x^y ビット単位で排他的OR (XOR)
x|y ビット単位でOR
x<y  x<=y  x>y  x>=y  x==y x!=y  x<>y
x is y   x is not y
x in s   x not in s
比較, 
識別(identity), 
要素検索(membership)
not x 真偽値の反転
x and y 真偽値のAND
x or y 真偽値のOR
優先順位 低 lambda args: expr 無名関数
  • ほとんどの名前はoperatorモジュールに定義されている (e.g. __add__ and add for +)
  • 多くのオペレータを上書き(オーバーライド)できます。

Basic types and their operations

Comparisons (defined between any types)

Comparisons
Comparison Meaning
Notes
< 厳密な 小なり
(1)
<= より小さい か 等しい  
> 厳密な 大なり  
>= より大きい か 等しい  
== 等しい  
!= or <> 等しくない, 不等  
is オブジェクトの識別(identity)
(2)
is not オブジェクトの識別を反転
(2)
Notes:
  • 比較演算子の振る舞いは上書きが可能です。上書きは、与えられたクラスのスペシャルメソッド __cmp__ を定義することで可能です。
  • (1) X < Y < Z < W は、期待された意味のとおりに振舞います。これはC言語と異なる部分です。
  • (2) オブジェクトの識別値(アドレス)を比較します (例 id(object)), オブジェクトの値の比較ではありません。

None

  • None は関数のデフォルトの返り値として使用されています。 NoneType型の組み込みの単一オブジェクトです。 将来、予約語に指定されるでしょう。
  • Input は None を評価しますが、Pythonをインタラクティブモードで動かしていた場合は何も出力されません。
  • 現在 None は定数(constant)になっています; "None" に値を代入すると、現在は文法エラーになります。

Boolean operators

Boolean values and operators
Value or Operator Evaluates to
Notes
built-in bool(expr) True if expr is true, False otherwise.
None, numeric zeros, empty sequences and mappings considered False  
all other values considered True  
not x True if x is False, else False  
x or y if x is False then y, else x
(1)
x and y if x is False then x, else y
(1)
Notes:
  • 与えられたクラスの Truth testing の振る舞いは、スペシャル・メソッド __nonzero__ を定義することで上書きが可能です。
  • (1) 第二引数 y の評価は、第一引数 x の評価だけでは結果が確定できない場合にのみ実行されます。

Numeric types

Floats, integers, long integers, Decimals.

  • Floats (type float) は C言語のdouble型で実装されています。
  • Integers (type int) は C言語のlong型で実装されています。(符号付き 32 bits, 最大値は sys.maxint)
  • Long integers (type long) は値に制限がありません (唯一、システムリソースによる制限をうけます)。
  • Integers と long integers は リリース 2.2 から 統合 が始められています (もはや末尾に L をつける必要はありません). int()OverflowError例外を出す代わりに long integer を返します. 次のような、オーバーフローを起こす演算 2<<32 は、もはや FutureWarning を引き起こすことはなく、long integer を返します.
  • 2.4 から、新しい型 Decimal が導入されました (参照: decimal). これは浮動点小数型にあるいくつかの制限、特に分数に関する制限を補います. float とは異なり、decimal numbers は厳密に表現されます; 演算において厳密性が維持されます; precision はContext type を通じて、ユーザによる設定が可能です [PEP 327].

Operators on all numeric types

Operators on all numeric types
Operation Result
abs(x) x の絶対値
int(x) x を整数型(integer)に変換
long(x) x を長整数型(long integer)に変換
float(x) x を浮動小数点数(floating point)に変換
-x x を負にする。
+x 何もしない(x unchanged)
x + y xy の和
x - y xy の差
x * y xy の積
x / y x ÷ y 厳密な商: 1/2 -> 0.5 (1)
x // y x ÷ y 浮動小数による商: 1//2 -> 0 (1)
x % y x / y の余り
divmod(x, y) タプル (x/y, x%y) を返す
x ** y xy 乗 (pow(x,y) と同じ)
Notes:
  • (1) インポート文 from __future__ import division が有効になっていない限り、まだ / は浮動小数の商(1/2 == 0) を返します。 
  • 各演算子の再定義は、クラスメソッド __truediv__ と __floordiv__ の上書き(override)で実現できます。

整数と長整数におけるビット演算子

Bit operators
Operation Result
~x x の全bitを反転
x ^ y xy をビット単位で排他的OR
x & y xy のビット単位でAND
x | y xy をビット単位でOR
x << n x を n ビット 左シフト
x >> n x を n ビット 右シフト

Complex Numbers

  • 複素数(complex)型は, マシンレベルの倍精度浮動小数点数のペアで表現されます。
  • 複素数 z の実数部と虚数部の値はアトリビュート z.realz.imag を用いて取得します。

Numeric exceptions

TypeError
非数値型に対する数値演算を行った場合に通知される
OverflowError
数値の境界を超えた場合
ZeroDivisionError
割り算かモジュロオペレータの第二引数がゼロであった場合に通知される

Operations on all sequence types (lists, tuples, strings)

Operations on all sequence types
Operation Result
Notes
x in s 要素のうち、一つでも x と等しい場合は True , それ以外は False
(3)
x not in s 要素のうち、一つでも x と等しい場合は False , それ以外は True
(3)
s1 + s2 s1s2 の連結  
s * n, n*s s のコピーn 個を連結
 
s[i] si' 番目の要素, 0 から数える
(1)
s[i: j]
s[i: j:step]
s のスライス i (含む) から j(除外) まで.
オプションの値 step は, マイナスも可能(default: 1).
(1), (2)
len(s) s の長さ  
min(s) s の最小値
 
max(s) s の最大値
 
reversed(s) [2.4] 逆順の イテレータ を返す. s は必ずシーケンスでなくてはならない, イテレータは不可 (そのような場合、代わりに reversed(list(s)) を使う. [PEP 322]
 
sorted(iterable [, cmp]
  [, cmp=cmpFct]
  [, key=keyGetter]
  [, reverse=bool])
[2.4] 要素入れ替え式(in-place)の新しい list.sort() と同じように作用する, 対して sorts はリストを iterable から新たに生成する.
 
Notes:
  • (1) もし ij がマイナスだった場合, インデックスはstringの終端から数えるので, 例えば len(s)+i または len(s)+j は置換される. しかし -0 は 0 のままなので注意する事.
  • (2) si から j までのスライスは、 i<= k < j を満たすインデックス k を持ったシーケンスとして定義されています.
    もし ij  len(s) よりも大きい場合, len(s) が使用されます.  j が省略された場合, len(s) が使用されます.  ij と等しいかより大きい場合, スライスは空になります.
  • (3) stringについて: 2.3 より以前は, x は単一のキャラクタ文字列でなくてはいけませんでした; 2.3 以降, x in s は x が s の部分文字列であれば True を返すようになっています.

Operations on mutable sequences (type list)

Operations on mutable sequences
Operation Result
Notes
s[i] =x s の要素番号 ix で置き換え  
s[i:j [:step]] = t s のスライス i から j までを t で置き換え  
del s[i:j[:step]] s[i:j] = []  と同じ  
s.append(x) s[len(s) : len(s)] = [x]  と同じ  
s.extend(x) s[len(s):len(s)]= x  と同じ
(5)
s.count(x) 次の条件 s[i] == x を満たす i の個数を返す  
s.index(x[, start[, stop]]) 条件 s[i]==x を満たす最小のインデックス i を返す. startstop の指定はリストを探索する範囲を制限する.
(1)
s.insert(i, x) s[i:i] = [x] if i>= 0  と同じ. i == -1 のとき最後の要素より前の位置に挿入される.  
s.remove(x) del s[s.index(x)]  と同じ
(1)
s.pop([i]) x = s[i]; del s[i]; return x  と同じ
(4)
s.reverse() s の要素列を逆順に書き換える
(3)
s.sort([cmp ])
s.sort([cmp=cmpFct]
  [, key=keyGetter]
  [, reverse=bool])
s の要素列を整列して書き換える
(2), (3)
Notes:
  • (1) s から x が発見できなかった場合、例外 ValueError が通知されます (i.e. out of range).
  • (2) sort() メソッドはオプション引数 cmp をもちます。cmp  は比較関数であり、引数としてをリストを2つとり、第一引数と第二引数の比較した結果 未満, 等値, より大きい を考慮し、返り値 -1, 0, or 1 を返します. 比較関数によってはソーティング・プロセスがかなり遅くなってしまう事に注意すること. 2.4から, cmp 引数はキーワードとして指定され, さらに2つのオプションキーワードが追加されました: 1つ目は関数 key であり、リスト要素を受け取り、比較で使われるkeyを返します (cmpよりも速い); 2つ目は reverse: これがTrueのとき, 比較に用いる論理を反転します.
    Python 2.3 より(?), sortは"静的"である事が保証されています. これは、同じキーをもつ2つのエントリーが、インプットされた順序と同じ順番で返される事を意味します. 例えば、最初に人物リストを名前順にソートし、次に年齢順でソートした場合, この操作の結果リストは、年齢順にソートされて同年齢の箇所は名前順にソートされた状態になります.
  • (3) sort()メソッド と reverse()メソッド はリストそのもの書き換えます. これは、巨大なリストをソートしたり逆順にする際に領域を節約できるようにする為です. この副作用を覚えておくこと. これらのメソッドの返り値はソートされたリストや逆順化されたリストではありません.
  • (4) pop()メソッド はリスト以外の変更可能なシーケンス・タイプではサポートされていません. オプション引数 i は -1 がデフォルトです, したがってデフォルトでは、リスト末尾の要素が消去され返り値として渡されます.
  • (5) x がリストオブジェクトでなかった場合、例外TypeError が通知されます.

Operations on mappings / dictionaries (type dict)

Operations on mappings
Operation Result
Notes
len(d) d がもつ要素の数  
dict()
dict(**kwargs)
dict(iterable)
dict(d)
空の辞書(dictionary)を生成.
辞書を生成, キーワード引数 kwargs で初期化.
辞書を生成, iterable から供給される (key, value) のペアで初期化.
辞書を生成, 辞書 dをコピーする.
 
d.fromkeys(iterable, value=None) 辞書を生成するクラスメソッド, iterator から供給される key を設定し, 値はすべて value にする.  
d[k] 要素の指定: d のキー k
(1)
d[k] = x d[k] に x を代入  
del d[k] d から d[k] を削除
(1)
d.clear() d の全要素を削除  
d.copy() d の 浅い コピー  
d.has_key(k)
k in d
d にキー k が存在していれば True, それ以外の場合 False  
d.items() A copy of d's list of (key, item) pairs
(2)
d.keys() A copy of d's list of keys
(2)
d1.update(d2) for k, v in d2.items(): d1[k] = v
Since 2.4, update(**kwargs) and update(iterable) may also be used.
d.values() A copy of d's list of values
(2)
d.get(k, defaultval) The item of d with key k
(3)
d.setdefault(k[,defaultval]) d[k] if k in d, else defaultval(also setting it)
(4)
d.iteritems() Returns an iterator over (key, value) pairs.  
d.iterkeys() Returns an iterator over the mapping's keys.  
d.itervalues() Returns an iterator over the mapping's values.  
d.pop(k[, default]) Removes key k and returns the corresponding value. If key is not found, default is returned if given, otherwise KeyError is raised.  
d.popitem() Removes and returns an arbitrary (key, value) pair from d
 
Notes:
  • keyが受け取れる型でなかった場合、TypeErrorが通知されます.
  • (1) mapにkeyが含まれていなかった場合、KeyErrorが通知されます.
  • (2) Key と value はランダムな順序で並んでいます.
  • (3) k がmapに含まれていなかった場合でも、例外は通知されません, 代わりに defaultval を返します. defaultval はオプション引数です, defaultval が引数として与えられておらず k がmapに含まれなかった場合, None が返されます.
  • (4) k がmapに含まれていなかった場合でも、例外は通知されません, 代わりに defaultval を返します, さらに 値 defaultVal と組にしてk をmapに加えます. defaultVal はオプション引数です. defaultVal が与えられておらず k がmapに含まれていない場合, None が返され、mapにも None が加えられます.

Operations on strings (types str & unicode)

以下のstringメソッドは豊富に用意されており(けれども完全ではない) string モジュールにある関数群の代替となります。
str型 と unicode型は、共通のベースクラス basestring を共有しています
Operations on strings
Operation Result
Notes
s.capitalize() s のコピーを返す. 先頭文字だけ大文字化する.  
s.center(width) s のコピーを返す. 文字列を中央揃え.
(1)
s.count(sub[ ,start[,end]]) 文字列 s に含まれるサブ文字列 sub の数を返す.
(2)
s.decode([ encoding[,errors]]) str s を codec (encoding) でデコードした unicode 文字列を返す. ファイルもしくは str のみ扱うI/O関数などから読み込む際に便利である.  encode と逆の操作を行う.
(3)
s.encode([ encoding[,errors]]) s をエンコードした文字列を str 形式で返す. たいがいは unicode 文字列を str にエンコードして表示したりファイルに書き出したりするのに使う (これらのI/O関数が str しか受け付けない為). また str to a str 型のエンコードにも使用される, 例 zip (codec 'zip') や uuencode (codec 'uu') する場合. decode の逆の操作をする.
(3)
s.endswith(suffix [,start[,end]]) s が指令された suffix でおわっていた場合に True を返す, そうでない場合 False を返す.
(2)
s.expandtabs([ tabsize]) s のコピーを返す. その際, 全てのタブ文字を空白文字(space)で展開し置き換える.
(4)
s.find(sub[ ,start[,end]]) s からサブ文字列 sub が最初に見つかった位置を返す. sub が見つからなかった場合 -1 を返す.
(2)
s.index(sub[ ,start[,end]]) find() と同じだが, サブ文字列が見つからなかった場合に ValueError例外を通知する.
(2)
s.isalnum() s の全文字が アルファベットか数字 である場合 True. そうでない場合 False.
(5)
s.isalpha() s の全文字が アルファベット である場合 True. そうでない場合 False.
(5)
s.isdigit() s の全文字が 数字 である場合 True. そうでない場合 False.
(5)
s.islower() s の全文字が 小文字 である場合 True. そうでない場合 False.
(6)
s.isspace() s の全文字が 空白文字 である場合 True. そうでない場合 False.
(5)
s.istitle() 文字列 s が 先頭だけ大文字(titlecased) である場合 True. そうでない場合 False.
(7)
s.isupper() s の全文字が 大文字 である場合 True. そうでない場合 False.
(6)
separator.join(seq) シーケンス seq の文字列を結合して 返す, 区切り文字列 に separator を使用する. 例: ",".join(['A', 'B', 'C']) -> "A,B,C"
 
s.ljust/rjust/center(width[, fillChar=' ']) s を長さ width 内で 右寄せ/左寄せ/中央ぞろえ した文字列を返す.
(1), (8)
s.lower() 小文字に変換した s のコピーを返す.
 
s.lstrip([chars] ) s のコピーを返す, 先頭から文字列 chars を削除. (default: 空白文字(blank chars))
 
s.replace(old, new[, maxCount =-1]) Returns a copy of s with the first maxCount (-1: unlimited) occurrences of substring old replaced by new.
(9)
s.rfind(sub[ , start[, end]]) Returns the highest index in s where substring sub is found. Returns -1 if sub is not found.
(2)
s.rindex(sub[ , start[, end]]) like rfind(), but raises ValueError when the substring is not found.
(2)
s.rstrip([chars]) Returns a copy of s with trailing chars(default: blank chars) removed.
 
s.split([ separator[, maxsplit]]) s に含まれる単語のリストを返す, separator を区切り文字とする.
(10)
s.rsplit([ separator[, maxsplit]]) split と同じだが, 分割操作を文字列の末尾から開始する.
(10)
s.splitlines([ keepends]) s に含まれる行のリストを返す, 行の境界で分割.
(11)
s.startswith(prefix [, start[, end]]) Returns True if s starts with the specified prefix, otherwise returns False. Negative numbers may be used for start and end
(2)
s.strip([chars]) Returns a copy of s with leading and trailing chars(default: blank chars) removed.
 
s.swapcase() Returns a copy of s with uppercase characters converted to lowercase and vice versa.
 
s.title() Returns a titlecased copy of s, i.e. words start with uppercase characters, all remaining cased characters are lowercase.
 
s.translate(table [, deletechars]) Returns a copy of s mapped through translation table table.
(12)
s.upper() Returns a copy of s converted to uppercase.
 
s.zfill(width) Returns the numeric string left filled with zeros in a string of length width.  
Notes:
  • (1) 空白を用いて詰め物(Padding)がなされます, もしくは与えられた文字で詰め物をします.
  • (2) オプション引数 start が与えられていた場合, 文字列の切り出し操作 s[start:] がおこなわれます. オプション引数 startend が与えられた場合, 文字列切り出し操作 s[start:end] がおこなわれます.
  • (3) デフォルト・エンコーディングは sys.getdefaultencoding() です, デフォルト・エンコーディングは sys.setdefaultencoding() によって変更できます. オプション引数 error を与えることで異なるエラーハンドリング・スキームをセットできます. 標準では errors'strict' がセットされており, これによってエンコーディング・エラーから ValueError が通知されます. 他に設定可能な値として 'ignore''replace' を選べます. モジュール codecs も参照のこと.
  • (4) オプション引数 tabsize が与えられていない場合, タブのサイズは半角8文字分が初期値になります.
  • (5) string s に1文字も含まれていない場合、False が返されます.
  • (6) string s に大文字が1文字も含まれていない場合、False が返されます.
  • (7) titlecased string は、単語の先頭のみ大文字になっています。大文字に続く文字が小文字だけで、小文字に続く文字が小文字だけ、の文字列です.
  • (8) width が len(s) より小さければ、s が返されます.
  • (9) オプション引数 maxCount が与えられた場合, 置換は maxCount に最初に達する箇所までしかおこなわれません. 
  • (10) separator が指定されていないか None である場合, 空白文字列が separator とします. maxsplit が与えられている場合, リストへ分割する最大回数が maxsplit で指定した回数までに制限されます.
  • (11) keependsTrue を与えない限り、splitlines()が返すリストに改行文字は含まれません.
  • (12) table は長さ256の文字列でなくてはならない. オプション引数 deletechars に存在する全てのキャラクタは、変換操作よりも優先して削除される.

String formatting with the % operator

formatString % args --> evaluates to a string
  • formatString は、ノーマル・テキスト と C言語の printf format fields を合わせたものです:
    %[flag][width][.precision] formatCode
    formatCode には c, s, i, d, u, o, x, X, e, E, f, g, G, r, % の内いづれかが置かれます(下記の表を参照).
  • flag キャラクタには -, +, 空白(blank), #, 0 を置くことができます (下記の表を参照).
  • Widthprecision* を置くことで、数値型引数から実際の字幅(width)と小数以下の有効桁数(precision)を指定できます. 以下は widthprecision の例:
    Examples
    Format string Result
    '%3d' % 2     
     '  2'
    '%*d' % (3, 2)
     '  2'
    '%-3d' % 2    
     '2  '
    '%03d' % 2    
     '002'
    '% d' % 2     
     ' 2'
    '%+d' % 2     
     '+2'
    '%+3d' % -2   
     ' -2'
    '%- 5d' % 2   
     ' 2   '
    '%.4f' % 2    
     '2.0000'
    '%.*f' % (4, 2) 
     '2.0000'
    '%0*.*f' % (10, 4, 2) 
     '00002.0000'
    '%10.4f' % 2  
     '    2.0000'
    '%010.4f' % 2 
     '00002.0000'
  • %s は、どんな型の引数も string に変換します (str() 関数を使用している)
  • args には取り得る引数は、単一の値 もしくは タプル です
    '%s has %03d quote types.' % ('Python', 2)  == 'Python has 002 quote types.'
  • 右辺の記述は 辞書形式(mapping) にすることもできます:
    a = '%(lang)s has %(c)03d quote types.' % {'c':2, 'lang':'Python'}
    (vars() 関数を右辺に使用すると、とても便利です)

Format codes
Code Meaning
d decimal  符号付き整数. 
i decimal  符号付き整数.
o 符号無し 8進数.
u decimal  符号無し.
x 符号無し 16進数 (小文字表記).
X 符号無し 16進数  (大文字表記).
e 浮動小数点数の指数表現 (小文字表記).
E 浮動小数点数の指数表現 (大文字表記).
f 浮動小数点数の小数点表現.
F 浮動小数点数の小数点表現.
g 指数部分が -4 より大きいなら "e" と同じ, 小さいならば 有効桁を表示, それ以外は "f".
G 指数部分が -4 より大きいなら "E" と同じ, 小さいならば 有効桁を表示, それ以外は "F".
c 1文字表示 (integer か 1文字のstringをとる).
r 文字列(String) (任意のpythonオブジェクトを repr() で変換).
s 文字列 (任意のpythonオブジェクトを str() で変換).
% 変換引数なし,  文字 "%" を出力します. (完全な記述による指定方法は %% です.)
Conversion flag characters
Flag Meaning
# The value conversion will use the "alternate form".
0 変換時に0をつめる.
- The converted value is left adjusted (overrides "-").
  (a space) A blank should be left before a positive number (or empty string) produced by a signed conversion.
+ A sign character ("+" or "-") will precede the conversion (overrides a "space" flag).

String templating

2.4 より [PEP 292]  stringモジュールは、template 文字列に変数を置き換え代入する新しいメカニズムを提供されました.
置き換え用の変数は $ で開始します. 実際の値は substitute or safe_substitute メソッドにより dictionary から与えられます (もしキーが見つからなかった場合 substitute は 例外 KeyError を投げます, また safe_substitute はキーがなくても無視します) :

  t = string.Template('Hello $name, you won $$$amount') # (メモ: $$ は、文字 $ を表します)
  t.substitute({'name': 'Eric', 'amount': 100000}) # -> u'Hello Eric, you won $100000'

File objects

(file型). 組み込みの関数 open() [preferred] か、open()のエイリアス file()によって生成されます. ほかのモジュールの関数からも同様に可能でしょう.
現在、ファイル名を受け取り・返す全ての関数で Unicode のファイル名がサポートされています (open, os.listdir, etc...).

Operators on file objects

File operations
Operation Result
f.close() ファイル f をクローズ.
f.fileno() ファイル f の fileno (fd) を得る .
f.flush() ファイル f'の内部バッファをフラッシュする.
f.isatty() ファイル f が tty-like デバイスに接続されていれば 1, それ以外は 0 を返す.
f.read([size]) 最大で size bytes まで、ファイル f から読み出し stringオブジェクトとして返す. 引数 size が与えられていない場合, EOF まで読む.
f.readline() f から1行読み込む. 返された行は \n の手がかりをもつ, ただし EOF である可能性は除く.
f.readlines() readline() を使用して EOF まで読み込む. 読み込んだ行をリストとして返す.
f.xreadlines() ファイル全体をメモリに格納せず、行単位で読み込むために sequence-like オブジェクトを返す. 2.2 以降は: for line in f  を推奨 (以下を参照のこと).
for line in f: do something... ファイルを行単位でイテレート(Iterate)する  (readline を使用)
f.seek(offset[, whence=0]) ファイル f の位置をセットする, C言語の stdio.h にある "fseek()" と同じ.
whence == 0 ならば ファイル先頭からインデクシングをおこなう.
whence == 1 ならば 現在位置から.
whence == 2 ならば ファイル末尾から.
f.tell() ファイル f の現在位置を返す (byte offset で計算).
f.write(str) ファイル f に文字列を書き込む.
f.writelines(list) ファイル f に文字列のリストを書き込む. EOL は付加されない.

File Exceptions

EOFError
読み込み中にファイル末尾(End-of-file)に達したことを示す例外 (何度も通知される可能性あり, 例: f が tty である場合など).
IOError
その他のI/O関連のI/O操作の失敗を示す

Sets

2.4 から, Python に高速なC言語による高速な実装をおこなった新たな組み込みの型が2つ加わりました [PEP 218]: setfrozenset (変更不可能な set) です. Sets は 順番のない(unordered) ユニークな(重複無しの)要素のコレクションです. エレメント(Elements) は ハッシュ可能です(hashable). frozensets はハッシュ可能 (したがって他のsetのエレメントになりうる) ですが sets はハッシュ不可能です. すべての sets は iterable です.

2.3 より, Setクラス と ImmutableSetクラス がモジュール sets に存在します. このモジュールは 2.4 において, std ライブラリの組み込み型に追加される形で残っています.
Main Set operations
Operation Result
set/frozenset([iterable=None]) [using built-in types] Builds a set or frozenset from the given iterable (default: empty), e.g. set([1,2,3]), set("hello").
Set/ImmutableSet([iterable=None]) [using the sets module] Builds a Set or ImmutableSet from the given iterable (default: empty), e.g. Set([1,2,3]).
len(s) Cardinality of set s.
elt in s / not in s True if element elt belongs / does not belong to set s.
for elt in s: process elt... Iterates on elements of set s.
s1.issubset(s2) True if every element in s1 is in s2.
s1.issuperset(s2) True if every element in s2 is in s1.
s.add(elt) Adds element elt to set s (if it doesn't already exist).
s.remove(elt) Removes element elt from set s. KeyError if element not found.
s.clear() Removes all elements from this set (not on immutable sets!).
s1.intersection(s2) or s1&s2 Returns a new Set with elements common to s1 and s2.
s1.union(s2) or s1|s2 Returns a new Set with elements from both s1 and s2.
s1.difference(s2) or s1-s2 Returns a new Set with elements in s1 but not in s2.
s1.symmetric_difference(s2) or s1^s2 Returns a new Set with elements in either s1 or s2 but not both.
s.copy() Returns a shallow copy of set s.
s.update(iterable) Adds all values from iterable to set s.

Advanced Types

- See manuals for more details -
  • Module objects
  • Class objects
  • Class instance objects
  • Type objects (see module: types)
  • File objects (see above)
  • Slice objects
  • Ellipsis object, used by extended slice notation (unique, named Ellipsis)
  • Null object (unique, named None)
  • XRange objects
  • Callable types:
    • User-defined (written in Python):
      • User-defined Function objects
      • User-defined Method objects
    • Built-in (written in C):
      • Built-in Function objects
      • Built-in Method object
  • Internal Types:
    • Code objects (byte-compile executable Python code: bytecode)
    • Frame objects (execution frames)
    • Traceback objects (stack trace of an exception)

Statements


Statement Result
pass Null ステートメント. 何もしない.
del name[, name]* オブジェクトと name 間の、参照の関連付けを取り消す. 全く参照されなくなったオブジェクトは間接的に(又、自動的に)削除される.
print[>> fileobject,] [s1 [, s2 ]* [,] sys.stdout もしくは fileobject に書き出し. 引数の間に空白を挿入する. ステートメントの末尾が comma でない場合は改行する. インタラクティブ・モード中では Print は必要ない, 単に式(expression)をタイプするだけで値が出力される, ただし値が None でない場合に限る.
exec x [in globals [, locals]] x を in 以下の名前空間内で実行. 標準では現在の名前空間で実行される. x は string, fileオブジェクトか functionオブジェクトでなくてはいけない. locals は Python標準の dict である必要はなく, 任意の mapping型 をとることができる.
callable(value,... [id=value] , [*args], [**kw]) 関数 callable に引数を与えてコールする. 引数は name で与える, 関数で標準の引数の値が定義されていれば省略も可能である. 例:  callable が   "def callable(p1=1, p2=2)"  と定義されていた場合
"callable()" <=> "callable(1, 2)"
"callable(10)" <=> "callable(10, 2)"
"callable(p2=99)" <=> "callable(1, 99)"
*args は positional 引数のタプル.
**kwkeyword 引数の辞書(dictionary).

Assignment operators

Assignment operators
Operator Result
Notes
a = b 基本的なアサイン - オブジェクト b を ラベル a に割り当てる
(1)(2)
a += b ほぼ同じな記述  a = a + b
(3)
a -= b ほぼ同じな記述  a = a - b
(3)
a *= b ほぼ同じな記述  a = a * b
(3)
a /= b ほぼ同じな記述  a = a / b
(3)
a //= b ほぼ同じな記述  a = a // b
(3)
a %= b ほぼ同じな記述  a = a % b
(3)
a **= b ほぼ同じな記述  a = a ** b
(3)
a &= b ほぼ同じな記述  a = a & b
(3)
a |= b ほぼ同じな記述  a = a | b
(3)
a ^= b ほぼ同じな記述  a = a ^ b
(3)
a >>= b ほぼ同じな記述  a = a >> b
(3)
a <<= b ほぼ同じな記述  a = a << b
(3)
Notes:
  • (1) では tuple, list, string を展開可能です:
    first, second = l[0:2]    # 等価な表現: first=l[0]; second=l[1]
    [f, s] = range(2)    # 
    等価な表現: f=0; s=1
    c1,c2,c3 = 'abc'    # 
    等価な表現: c1='a'; c2='b'; c3='c'
    (a, b), c, (d, e, f) = ['ab', 'c', 'def']    # 
    等価な表現: a='a'; b='b'; c='c'; d='d'; e='e'; f='f'
    Tip: x,y = y,xxy の交換(swap)です.
  • (2) 複数の代入が可能:
    a = b = c = 0
    list1 = list2 = [1, 2, 3]    # list1 と list2 が同じリストを参照する (l1 is l2)
  • (3) 厳密には等価な記述ではない - a の評価は一度切りである. また, 可能な場合には, in-place方式の処理が行われる - a の置き換えではなく書き換えがおこなわれる.

Control Flow statements

Control flow statements
Statement Result
if condition:
  suite
[elif condition:   suite]*
[else:
  suite]
一般的な if/else if/else の構文
while condition:
  suite
[else:
  suite]
while 構文. The else はループ終了後に実行される, ただし break でループを抜けた場合は実行されない.
for element in sequence:
  suite
[else:
  suite]
sequence の各要素を element に割り当てつつ繰り返し実行(iterate). 数列を生成して繰り返す場合は 組み込み関数range を使用するとよい. else suitebreak 以外でのループ終了時に実行される.
break forwhile ループをただちに抜ける.
continue forwhile ループ内で, 直ちに次のイテレーションへ移行する.
return [result] Exits from 関数 (もしくは メソッド) を終了し result を返す (2個以上の値を返す場合は タプル(tuple) を使用する). result が与えられていない場合は, None を返す.
yield expression (generator 関数の内部で, かつ try..finally ブロックのtryの外でのみ使用される, ). 評価された 式(expression) を "返す".

Exception statements

Exception statements
Statement Result
assert expr[, message] expr を評価する. false であった場合, 例外 AssertionError をメッセージと共に通知する. 2.3 より前では, __debug__ が 0 の時に抑制される.
try:
  suite1
[except [exception [, value]:
  suite2]+
[else:
  suite3]
suite1 のステートメントが実行される. 例外が発生した場合, except節に列挙された中から該当する例外(exception)を探す. 例外がマッチするか except のみ記述されていた場合,  その節の suite を実行する. 例外が発生しなかった場合, else ブロックが suite1 に続いて実行される. 例外(exception)が値を持っていた場合, 変数 value に代入される. exception には複数の例外のリストをタプル(tuple)で記述できる, 例 except(KeyError, NameError), val: print val.
try:
  suite1
finally:
  suite2
suite1 に記述されたステートメントが実行される. 例外が発生しなかった場合, suite2 を実行 (suite1return,break もしくは continue ステートメントで終了していても実行される). 例外が発生した場合, suite2 を実行し, 直後に例外を再び発生させる.
raise exceptionInstance Exception の派生クラスのインスタンスを発生させる (raise の好ましい やり方).
raise exceptionClass [, value [, traceback]] 例外クラス(exceptionClass) をオプション引数 value を伴って発生させる. 例外のバックトレースを表示する場合, 引数 traceback でトレースバック・オブジェクトを指定する.
raise 引数無しの raise ステートメントを実行すると, 現在の関数で発生した 直前の例外(last exception) を再度発生させる.
  • 例外は例外クラス(exception class)のインスタンスである (2.0より前では, 単なる文字列(string)であったようだ).
  • 例外クラスは 定義済みクラス:Exception から派生したものでなくてはいけません, 例:
    class TextException(Exception): pass
    try:
    if bad:
    raise TextException()
    except Exception:
    print 'Oops' # TextExceptionがExceptionのサブクラスであるので、この文は実行される
  • 予期されていない例外によってエラーメッセージが出力される場合, クラス名が出力され, コロンとスペースに続いて 組み込み関数str()で文字列化されたインスタンスが出力される.
  • すべての組み込み例外クラスはStandardErrorから派生されている, StandardError自体はExceptionの派生クラスである.

Name Space Statements

インポートするモジュール・ファイルは Python path (sys.path) にリストされたディレクトリに置かれている必要があります. 2.3 以降では, zip ファイルを指定することもできます [例 sys.path.insert(0, "theZipFile.zip")].

Packages (>1.5): package は名前空間であり, 複数のモジュールと特別な初期化モジュール __init__.py (空でもよい) の置かれたディレクトリにマップされます.
Packages/directories は入れ子にすることができます. モジュールのシンボルを [package.[package...].module.symbol のような形式で指定できます.
[1.51: MacとWindows環境では, モジュール・ファイル名と import 文で使用するモジュール名の大・小文字が同じである必要があります.]

Name space statements
Statement Result
import module1 [as name1] [, module2]* モジュールをインポートする. Members of module must be referred to by qualifying with [package.]module name, e.g.:
import sys; print sys.argv
import package1.subpackage.module
package1.subpackage.module.foo()
as以下が記述されている場合, module1name1 にリネームされる.
from module import name1 [as othername1][, name2]* モジュール module から現在の名前空間にnamesをインポートする.
from sys import argv; print argv
from package1 import module; module.foo()
from package1.module import foo; foo()
as以下が記述されていた場合, name1othername1 にリネームされる.
[2.4] ステートメント from module import names の names のリストを括弧 '(' ')' で囲むことができる (PEP 328).
from module import * module にある 全ての names をインポートする, ただし "_" で始まるものは除く. 使用はなるべく避けること, 名前の破壊に注意!
from sys import *; print argv
from package.module import *; print x
モジュールの最上位レベルでのみ有効.
module__all__ アトリビュートが定義されている場合, __all__ に列挙されている名前のみがインポートされる.

注意: "from package import *" はパッケージの __init__.py ファイルに定義されているシンボルのみをインポートします, パッケージの各モジュール内にある __init__.py ではありません!
global name1 [, name2] Names are from global scope (usually meaning from module) rather than local (usually meaning only in function).
E.g. in function without global statements, assuming "x" is name that hasn't been used in function or module so far:
- Try to read from "x" -> NameError
- Try to write to "x" -> creates "x" local to function
If "x" not defined in fct, but is in module, then: - Try to read from "x", gets value from module
- Try to write to "x", creates "x" local to fct
But note "x[0]=3" starts with search for "x", will use to global "x" if no local "x".

Function Definition

def func_id ([param_list]):
suite
関数オブジェクトの生成して func_id という名前に関連付ける.
param_list ::= [id [, id]*]
id ::= value | id = value | *id | **id
引数は  で渡されます. したがって変更可能な(mutable)オブジェクトとして表現されている引数(入出力パラメータ)のみを書き換えることができます. 2つ以上の値を返す場合は タプル を使用します.

Example:
 def test (p1, p2 =5+3, *args, **kwargs):
  • "=" の付いている引数はデフォルトの値を持つ (評価は関数定義の時点でなされる).
  • 引数リストに "*args" がある場合, 関数に渡された非キーワード引数の残り全てが, タプルとして args にアサインされる.
  • 引数リストに "**kwargs" がある場合, 関数に渡されたキーワード引数の残り全てが, 辞書として kwargs にアサインされる.
  • argskwargs を名前に使用するのが一般的ですが, 他の名前を使用してもかまいません.

Class Definition

class className [(super_class1[, super_class2]*)]:
  suite

クラス・オブジェクトを生成し, 名前 className に関連付ける.
suite には クラス・メソッドのローカル定義"defs" と クラス・アトリビュートのアサインが含まれます.

Examples:
class MyClass (class1, class2): ...
class1 と class2 の両方から継承するクラスオブジェクトを生成. 新しいクラスオブジェクトを "MyClass" という名前に関連付ける.
class MyClass: ...
ベースクラスオブジェクトを生成 (何も継承しない). 新しいクラスオブジェクトを "MyClass" という名前に関連付ける.
class MyClass (object): ...
new-style class/typeの生成 (objectからの継承はnew-style classになる). 新しいクラスオブジェクトを "MyClass" という名前に関連付ける.

  • クラス・インスタンス・メソッドの第一引数(の操作)は, 常にターゲット・インスタンス・オブジェクトです, 規約では 'self' と呼ばれています.
  • 特別なスタティック・メソッド __new__(cls[,...]) はインスタンスが生成されたときに呼ばれます. 第一引数はクラスであり, 第二引数以降は __init__() へ渡されます, より詳細な説明は こちら を参照のこと.
  • 特別なメソッド __init__() はインスタンスが生成されたときに呼ばれます.
  • 特別なメソッド __del__() はオブジェクトに対する参照が無くなった時に呼ばれます.
  • クラス・オブジェクトを "コールする" ことによるインスタンスの生成では, 引数をとることができます (従って instance=apply(aClassObject, args...) のようにしてインスタンスを生成します!)
  • 2.2 より前では 組み込みクラス list, dict を継承するクラスを作成できませんでした (以前は UserDict や UserList モジュールを使用して, これらを "ラッピング" する必要がありました); 2.2 以降では list, dict を直に継承するクラスの作成が可能になっています (Types/Classes unification を参照).

Example:
class c (c_parent):
def __init__(self, name):
self.name = name
def print_name(self):
print "I'm", self.name
def call_parent(self):
c_parent.print_name(self)

instance = c('tom')
print instance.name
'tom'
instance.print_name()
"I'm tom"

Call parent's super class by accessing parent's method directly and passing "self" explicitly (see "call_parent" in example above).
他にも多くのスペシャル・メソッドが, 算術演算子, シーケンス, マッピング・インデクシング, などを実装するために用意されています.

Types / classes unification

ベース・タイプ int, float, str, list, tuple, dict, file は, 現在(2.2)は ベースクラス object を継承した class のように振舞います, さらにこれらを継承するサブクラスも作成できます:
x = int(2) # 組み込みのキャスト関数はベース・タイプのコンストラクタです
y = 3 # <=> int(3) (リテラルは新しいベース・タイプのインスタンスです)
print type(x), type(y) # int, int

assert isinstance(x, int) # isinstance(x, types.IntType) の置き換え

assert issubclass(int, object) # ベース・タイプは ベース・クラス 'object' を継承する.
s = "hello" # <=> str("hello")
assert isinstance(s, str)

f = 2.3 # <=> float(2.3)
class MyInt(int): pass # ベース・タイプのサブクラス
x,y = MyInt(1), MyInt("2")

print x, y, x+y # => 1,2,3

class MyList(list): pass

l = MyList("hello")

print l # ['h', 'e', 'l', 'l', 'o']
New-style class は object を継承します. Old-style class は継承しません.

Documentation Strings

モジュール, クラス, 関数 は, suiteの最初のステートメントに文字列リテラルを置くことでドキュメントを付加できます. ドキュメントはモジュール,クラス,関数の '__doc__' アトリビュートを取得することでretrieveできます.

Example:
class C:
"A description of C"
def __init__(self):
"A description of the constructor"
# etc.

c.__doc__ == "A description of C".
c.__init__.__doc__ == "A description of the constructor"

Iterators

  • イテレータ(iterator)コレクション(collection)の要素を列挙します. イテレータはメソッドnext()をもつオブジェクトであり, 次の要素を返すか 例外StopIteration を通知します.
  • 新しい組み込み関数 iter(obj) を使用すると obj のイテレータを取得できます, これは obj.__class__.__iter__() をコールします.
  • コレクションに __iter__()next() を実装すると, 独自のイテレータをもたせることができます.
  • 組み込みのコレクション (lists, tuples, strings, dict) には __iter__() が実装されています; 辞書型(maps) はキーを列挙します; file は 行単位で列挙します.
  • イテレータから listtuple を生成できます, 例 list(anIterator)
  • ループに使われる際はPythonは暗黙的にイテレータを使用します:
    • for elt in collection:
    • if elt in collection:
    • タプルへのアサイン: x,y,z= collection

Generators

  • ジェネレータ(generator) は呼び出しの間で状態を維持し呼び出しのたびに新しい値を生成します. キーワードyieldを使うことで呼出し毎に値が返されます(呼び出し一回につき一つ), また return もしくは StopIteration()例外 によって値の列挙が終了したことを通知します.
  • 典型的な使い方はID, 名前, シリアルナンバーの生成です.
  • ジェネレータを使うには: ジェネレータ関数をコールしてジェネレータ・オブジェクトを取得します, 次に generator.next() をコールして, 例外 StopIteration が発生するまで次の値を取得しつづけます.
  • 2.4 では ジェネレータ表現(generator expressions) が導入されました[PEP 289] ジェネレータ表現は リスト内包表記(list comprehensions) によく似ていますが, ジェネレータは呼び出しのたびに要素を1つ1つ生成する点が異なります, ジェネレータは長い順列などに適しています :
      linkGenerator = (link for link in get_all_links() if not link.followed)
      for link in linkGenerator:
        ...process link...

    ジェネレータ表現は必ず
    括弧()で囲まなければいけません.
  • 2.2では, 以下のステートメントによってジェネレータを有効にする必要があります: from __future__ import generators (2.3以降でこの操作をする必要はありません)

Example:
def genID(initialValue=0):
v = initialValue
while v < initialValue + 1000:
yield "ID_%05d" % v
v += 1
return # もしくは: raise StopIteration()

generator = genID() # ジェネレータの生成
for i in range(10): # 10個の値を生成(Generate)する
print generator.next()

Descriptors / Attribute access

  • ディスクリプタ(Descriptor)ディスクリプタ・プロトコル(descriptor protocol)を表現する最低3つのメソッドを実装したオブジェクトです :
    • __get__(self, obj, type=None) --> value
    • __set__(self, obj, value)
    • __delete__(self, obj)
    Pythonは (object の派生クラスなどの) new-style class の属性(attributes)やメソッドを記述したりアクセスしたりする際にディスクリプタを透過的に使用します. [より詳しい情報])
  • 組み込みのディスクリプタとして定義できるもの:
    • Static methods : staticmethod(f) を使用して メソッド f(x) を static (unbound) にします.
    • Class methods: static に似ていますが, 第一引数にClassをとります => f = classmethod(f) を使用して, メソッド f(theClass, x) をクラス・メソッドにします.
    • Properties : プロパティは新しいビルトイン型 property の インスタンスです, プロパティはアトリビュートのためのディスクリプタプロトコルを実装しています => propertyName = property(getter=None, setter=None, deleter=None, description=None) を使用して, クラスの内部または外部でプロパティを定義します. 定義した後は propertyName もしくは obj.propertyName でプロパティにアクセスします.
    • Slots. ニュー・スタイル・クラスでは __slots__ を使用したクラス・アトリビュートの定義により, 割り当て可能なアトリビュート名のリストを制限できます, これによってアトリビュート名のミスタイプを防止できます (ミスタイプをしてもPythonが発見してくれることは普通ないので, 新しいアトリビュートの生成を引き起こしてしまう), 例 __slots__ = ('x', 'y')
      Note: 最近の議論からすると, slot を使用する本当の目的はいまだ明確になっていないようです (最適化とか?), したがって slot を使うこともたぶん奨励されてはいないでしょう.

Decorators for functions & methods

  • [PEP 318] A decorator D is noted @D on the line preceding the function/method it decorates :
        @D
        def f(): ...
    上記は次のような記述と等価です:
        def f(): ...
        f = D(f)

  • 複数のデコレータを重ねて適用することもできます:
        @A @B @C
        def f(): ...
    上記は次のような記述と等価です:
        f = A(B(C(f)))
  • デコレータは単なる関数です. デコレート対象となる関数を引数にとり、同じ関数または呼び出し可能な新しいものを返します.
  • デコレータ関数は引数をとることができます:
        @A @B @C(args)
    上記は次のような表現になります:
        def f(): ...
        _deco = C(args)
        f = A(B(_deco(f)))

  • デコレータの記述 @staticmethod@classmethod は、等価な記述 f = staticmethod(f) と f = classmethod(f) をよりエレガントな形式に置き換えたものです.

Misc

lambda [param_list]: returnedExpr
無名の関数を生成します.
returnedExpr は式(expression)でなければいけません, 文(statement)は許されません (例えば, "if xx:...", "print xxx", などは不可.) これに加えて改行を含めることもできません. 多くの場合 lambda は filter(), map(), reduce() 関数や, GUIコールバック のために使用されます.

リスト内包表記(List comprehensions)
result = [expression for item1 in sequence1  [if condition1]
[for item2 in sequence2 ... for itemN in sequenceN]
]
上記は 次の記述と等価である:
result = []
for item1 in sequence1:
for item2 in sequence2:
...
for itemN in sequenceN:
if (condition1) and further conditions:
result.append(expression)

Nested scopes
2.2より、スコープの入れ子from __future__ import nested_scopes のように明示的に有効にする必要が無くなりました, スコープの入れ子は常に使用可能です.

Built-In Functions

組み込みの関数はモジュール _builtin__ に定義されおり、自動的にインポートされます.
Built-In Functions
Function Result
__import__(name[, globals[,locals[,from list]]]) 与えられたコンテキストの内部へモジュールをインポートします (詳細は library reference を参照)
abs(x) 数値 x の絶対値を返す.
apply(f, args[, keywords]) 引数 args と オプション・キーワード をともなって 関数/メソッド f を呼び出す. 2.3から廃止された, apply(func, args, keywords) の代わりに func(*args, **keywords) を使用すること [詳細をみる]
buffer(object[, offset[, size]]) object のスライスから Buffer を返す, 引数 object は(文字列, アレイ, バッファーなどの)バッファ呼び出しインタフェースをサポートしていなければならない. 非必須組み込み関数である,  [詳細をみる]
callable(x) x が呼び出し可能である場合 True, そうでない場合 False を返す.
chr(i) アスキーコードが整数 i となるような文字1字からなる文字列を返す.
classmethod(function) function のクラスメソッドを返す. クラスメソッドは, インスタンス・メソッドが暗黙の第一引数としてインスタンスをとるように, 第一引数としてクラスをとります. クラスメソッドの宣言は以下ように記述します:

  class C:
    def f(cls, arg1, arg2, ...): ...
    f = classmethod(f)


クラスメソッドの呼び出しは クラスから C.f() もしくは インスタンスから C().f() のようにおこないます. インスタンスから呼び出した場合, 所属クラスを除く情報以外は無視されます. 導出クラス(derived class)のクラスメソッドが呼び出された場合, 暗黙的な第一引数として導出クラスオブジェクトが渡されます.
Since 2.4より 代替としてdecorator構文が使用可能です:
  class C:
    @classmethod
    def f(cls, arg1, arg2, ...): ...
cmp(x,y) xy を比較した結果が < ならば 負, == ならば 0, > ならば 正 の値を返す.
coerce(x,y) Returns a tuple of the two numeric arguments converted to a common type. Non essential function, see [details]
compile(string, filename, kind[, flags[, dont_inherit]]) Compiles string into a code object. filename is used in error message, can be any string. It is usually the file from which the code was read, or eg. '<string>' if not read from file. kind can be 'eval' if string is a single stmt, or 'single' which prints the output of expression statements that evaluate to something else than None, or be 'exec'. New args flags and dont_inherit concern future statements.
complex(real[, image]) Creates a complex object (can also be done using J or j suffix, e.g. 1+3J).
delattr(obj, name) Deletes the attribute named name of object obj <=> del obj.name
dict([mapping-or-sequence]) Returns a new dictionary initialized from the optional argument (or an empty dictionary if no argument). Argument may be a sequence (or anything iterable) of pairs (key,value).
dir([object]) Without args, returns the list of names in the current local symbol table. With a module, class or class instance object as arg, returns the list of names in its attr. dictionary.
divmod(a,b) Returns tuple (a/b, a%b)
enumerate(iterable) Iterator returning pairs (index, value) of iterable, e.g. List(enumerate('Py')) -> [(0, 'P'), (1, 'y')].
eval(s[, globals[, locals]]) Evaluates string s, representing a single python expression, in (optional) globals, locals contexts. s must have no NUL's or newlines. s can also be a code object. locals can be any mapping type, not only a regular Python dict.
Example:
x = 1; assert eval('x + 1') == 2
(To execute statements rather than a single expression, use Python statement exec or built-in function execfile)
execfile(file[, globals[,locals]]) Executes a file without creating a new module, unlike import. locals can be any mapping type, not only a regular Python dict.
file(filename[,mode[,bufsize]]) Opens a file and returns a new file object. Alias for open.
filter(function,sequence) Constructs a list from those elements of sequence for which function returns true. function takes one parameter.
float(x) Converts a number or a string to floating point.
getattr(object,name[,default])) Gets attribute called name from object, e.g. getattr(x, 'f') <=> x.f). If not found, raises AttributeError or returns default if specified.
globals() Returns a dictionary containing the current global variables.
hasattr(object, name) Returns true if object has an attribute called name.
hash(object) Returns the hash value of the object (if it has one).
help([object]) Invokes the built-in help system. No argument -> interactive help; if object is a string (name of a module, function, class, method, keyword, or documentation topic), a help page is printed on the console; otherwise a help page on object is generated.
hex(x) Converts a number x to a hexadecimal string.
id(object) Returns a unique integer identifier for object.
input([prompt]) Prints prompt if given. Reads input and evaluates it. Uses line editing / history if module readline available.
int(x[, base]) Converts a number or a string to a plain integer. Optional base parameter specifies base from which to convert string values.
intern(aString) Enters aString in the table of interned strings and returns the string. Since 2.3, interned strings are no longer 'immortal' (never garbage collected), see [details]
isinstance(obj, classInfo) Returns true if obj is an instance of class classInfo or an object of type classInfo (classInfo may also be a tuple of classes or types). If issubclass(A,B) then isinstance(x,A) => isinstance(x,B)
issubclass(class1, class2) Returns true if class1 is derived from class2 (or if class1 is class2).
iter(obj[,sentinel]) Returns an iterator on obj. If sentinel is absent, obj must be a collection implementing either __iter__() or __getitem__(). If sentinel is given, obj will be called with no arg; if the value returned is equal to sentinel, StopIteration will be raised, otherwise the value will be returned. See Iterators.
len(obj) Returns the length (the number of items) of an object (sequence, dictionary, or instance of class implementing __len__).
list([seq]) Creates an empty list or a list with same elements as seq. seq may be a sequence, a container that supports iteration, or an iterator object. If seq is already a list, returns a copy of it.
locals() Returns a dictionary containing current local variables.
long(x[, base]) Converts a number or a string to a long integer. Optional base parameter specifies the base from which to convert string values.
map(function, sequence[, sequence, ...]) Returns a list of the results of applying function to each item from sequence(s). If more than one sequence is given, the function is called with an argument list consisting of the corresponding item of each sequence, substituting None for missing values when not all sequences have the same length. If function is None, returns a list of the items of the sequence (or a list of tuples if more than one sequence). => You might also consider using list comprehensions instead of map().
max(seq[, args...]) With a single argument seq, returns the largest item of a non-empty sequence (such as a string, tuple or list). With more than one argument, returns the largest of the arguments.
min(seq[, args...]) With a single argument seq, returns the smallest item of a non-empty sequence (such as a string, tuple or list). With more than one argument, returns the smallest of the arguments.
oct(x) Converts a number to an octal string.
open(filename [, mode='r', [bufsize]]) Returns a new file object. See also alias file(). Use codecs.open() instead to open an encoded file and provide transparent encoding / decoding.
  • filename is the file name to be opened
  • mode indicates how the file is to be opened:
    • 'r' for reading
    • 'w' for writing (truncating an existing file)
    • 'a' opens it for appending
    • '+' (appended to any of the previous modes) open the file for updating (note that 'w+'truncates the file)
    • 'b' (appended to any of the previous modes) open the file in binary mode
    • 'U' (or 'rU') open the file for reading in Universal Newline mode: all variants of EOL (CR, LF, CR+LF) will be translated to a single LF ('\n').
  • bufsize is 0 for unbuffered, 1 for line buffered, negative or omitted for system default, >1 for a buffer of (about) the given size.
ord(c) Returns integer ASCII value of c (a string of len 1). Works with Unicode char.
pow(x, y [, z]) Returns x to power y [modulo z]. See also ** operator.
range(start [,end [, step]]) Returns list of ints from >= start and < end.
With 1 arg, list from 0..arg-1
With 2 args, list from start..end-1
With 3 args, list from start up to end by step
raw_input([prompt]) Prints prompt if given, then reads string from std input (no trailing \n). See also input().
reduce(f, list [, init]) Applies the binary function f to the items of list so as to reduce the list to a single value. If init is given, it is "prepended" to list.
reload(module) Re-parses and re-initializes an already imported module. Useful in interactive mode, if you want to reload a module after fixing it. If module was syntactically correct but had an error in initialization, must import it one more time before calling reload().
repr(object) Returns a string containing a printable and if possible evaluable representation of an object. <=> `object` (using backquotes). Class redefinable (__repr__). See also str()
round(x, n=0) Returns the floating point value x rounded to n digits after the decimal point.
setattr(object, name, value) This is the counterpart of getattr().setattr(o, 'foobar', 3) <=> o.foobar = 3. Creates attribute if it doesn't exist!
slice([start,] stop[, step]) Returns a slice object representing a range, with R/O attributes: start, stop, step.
staticmethod(function) Returns a static method for function. A static method does not receive an implicit first argument. To declare a static method, use this idiom:

  class C:
    def f(arg1, arg2, ...): ...
    f = staticmethod(f)


Then call it on the class C.f() or on an instance C().f(). The instance is ignored except for its class.
Since 2.4 you can alternatively use the decorator notation:
  class C:
    @staticmethod
    def f(cls, arg1, arg2, ...): ...
str(object) Returns a string containing a nicely printable representation of an object. Class overridable (__str__). See also repr().
sum(iterable[, start=0]) Returns the sum of a sequence of numbers (not strings), plus the value of parameter. Returns start when the sequence is empty.
super( type[, object-or-type]) Returns the superclass of type. If the second argument is omitted the super object returned is unbound. If the second argument is an object, isinstance(obj, type) must be true. If the second argument is a type, issubclass(type2, type) must be true. Typical use:
class C(B):
  def meth(self, arg):
    super(C, self).meth(arg)
tuple([seq]) Creates an empty tuple or a tuple with same elements as seq. seq may be a sequence, a container that supports iteration, or an iterator object. If seq is already a tuple, returns itself (not a copy).
type(obj) Returns a type object [see module types] representing the type of obj. Example: import types if type(x) == types.StringType: print 'It is a string'. NB: it is better to use instead: if isinstance(x, types.StringType)...
unichr(code) Returns a unicode string 1 char long with given code.
unicode(string[, encoding[,error]]]) Creates a Unicode string from a 8-bit string, using the given encoding name and error treatment ('strict', 'ignore',or 'replace'}. For objects which provide a __unicode__() method, it will call this method without arguments to create a Unicode string.
vars([object]) Without arguments, returns a dictionary corresponding to the current local symbol table. With a module, class or class instance object as argument, returns a dictionary corresponding to the object's symbol table. Useful with the "%" string formatting operator.
xrange(start [, end [, step]]) Like range(), but doesn't actually store entire list all at once. Good to use in "for" loops when there is a big range and little memory.
zip(seq1[, seq2,...]) Returns a list of tuples where each tuple contains the nth element of each of the argument sequences. Since 2.4 returns an empty list if called with no arguments (was raising TypeError before).

Built-In Exception classes

Exception
The mother of all exceptions. exception.args is a tuple of the arguments passed to the constructor.
  • StopIteration
    Raised by an iterator's next() method to signal that there are no further values.
  • SystemExit
    On sys.exit()
  • Warning
    Base class for warnings (see module warning)
    • UserWarning
      Warning generated by user code.
    • PendingDeprecationWarning
      Warning about future deprecated code.
    • DeprecationWarning
      Warning about deprecated code.
    • SyntaxWarning
      Warning about dubious syntax.
    • RuntimeWarning
      Warning about dubious runtime behavior.
  • StandardError
    Base class for all built-in exceptions; derived from Exception root class.
    • ArithmeticError
      Base class for arithmetic errors.
      • FloatingPointError
        When a floating point operation fails.
      • OverflowError
        On excessively large arithmetic operation.
      • ZeroDivisionError
        On division or modulo operation with 0 as 2nd argument.
    • AssertionError
      When an assert statement fails.
    • AttributeError
      On attribute reference or assignment failure
  • EnvironmentError [new in 1.5.2]
    On error outside Python; error arg. tuple is (errno, errMsg...)
    • IOError [changed in 1.5.2]
      I/O-related operation failure.
    • OSError [new in 1.5.2]
      Used by the os module's os.error exception.
      • WindowsError
        When a Windows-specific error occurs or when the error number does not correspond to an errno value.
  • EOFError
    Immediate end-of-file hit by input() or raw_input()
  • ImportError
    On failure of import to find module or name.
  • KeyboardInterrupt
    On user entry of the interrupt key (often `CTRL-C')
  • LookupError
    base class for IndexError, KeyError
    • IndexError
      On out-of-range sequence subscript
    • KeyError
      On reference to a non-existent mapping (dict) key
  • MemoryError
    On recoverable memory exhaustion
  • NameError
    On failure to find a local or global (unqualified) name.
    • UnboundLocalError
      On reference to an unassigned local variable.
  • ReferenceError
    On attempt to access to a garbage-collected object via a weak reference proxy.
  • RuntimeError
    Obsolete catch-all; define a suitable error instead.
    • NotImplementedError [new in 1.5.2]
      On method not implemented.
  • SyntaxError
    On parser encountering a syntax error
    • IndentationError
      On parser encountering an indentation syntax error
    • TabError
      On parser encountering an indentation syntax error
  • SystemError
    On non-fatal interpreter error - bug - report it
  • TypeError
    On passing inappropriate type to built-in operator or function.
  • ValueError
    On argument error not covered by TypeError or more precise.
    • UnicodeError
      On Unicode-related encoding or decoding error.

Standard methods & operators redefinition in classes

Standard methods & operators map to special methods '__method__' and thus can be redefined (mostly in user-defined classes), e.g.:
class C:
def __init__(self, v): self.value = v
def __add__(self, r): return self.value + r

a = C(3) # sort of like calling C.__init__(a, 3)
a + 4 # is equivalent to a.__add__(4)

Special methods for any class
Method Description
__new__(cls[, ...]) Instance creation (on construction). If __new__ returns an instance of cls then __init__ is called with the rest of the arguments (...), otherwise __init__ is not invoked. More details here.
__init__(self, args) Instance initialization (on construction)
__del__(self) Called on object demise (refcount becomes 0)
__repr__(self) repr() and `...` conversions
__str__(self) str() and print statement
__cmp__(self,other) Compares self to other and returns <0, 0, or >0. Implements >, <, == etc...
__lt__(self, other) Called for self < other comparisons. Can return anything, or can raise an exception.
__le__(self, other) Called for self <= other comparisons. Can return anything, or can raise an exception.
__gt__(self, other) Called for self > other comparisons. Can return anything, or can raise an exception.
__ge__(self, other) Called for self >= other comparisons. Can return anything, or can raise an exception.
__eq__(self, other) Called for self == other comparisons. Can return anything, or can raise an exception.
__ne__(self, other) Called for self != other (and self <> other) comparisons. Can return anything, or can raise an exception.
__hash__(self) Compute a 32 bit hash code; hash() and dictionary ops
__nonzero__(self) Returns 0 or 1 for truth value testing. when this method is not defined, __len__() is called if defined; otherwise all class instances are considered "true".
__getattr__(self,name) Called when attribute lookup doesn't find name. See also __getattribute__.
__getattribute__( self, name) Same as __getattr__ but always called whenever the attribute name is accessed.
__setattr__(self, name, value) Called when setting an attribute (inside, don't use "self.name = value", use instead "self.__dict__[name] = value")
__delattr__(self, name) Called to delete attribute <name>.
__call__(self, *args, **kwargs) Called when an instance is called as function: obj(arg1, arg2, ...) is a shorthand for obj.__call__(arg1, arg2, ...).

Operators

See list in the operator module. Operator function names are provided with 2 variants, with or without leading & trailing '__' (e.g. __add__ or add).

Numeric operations special methods
Operator Special method
self + other __add__(self, other)
self - other __sub__(self, other)
self * other __mul__(self, other)
self / other __div__(self, other) or __truediv__(self,other) if __future__.division is active.
self // other __floordiv__(self, other)
self % other __mod__(self, other)
divmod(self,other) __divmod__(self, other)
self ** other __pow__(self, other)
self & other __and__(self, other)
self ^ other __xor__(self, other)
self | other __or__(self, other)
self << other __lshift__(self, other)
self >> other __rshift__(self, other)
nonzero(self) __nonzero__(self) (used in boolean testing)
-self __neg__(self)
+self __pos__(self)
abs(self) __abs__(self)
~self __invert__(self) (bitwise)
self += other __iadd__(self, other)
self -= other __isub__(self, other)
self *= other __imul__(self, other)
self /= other __idiv__(self, other) or __itruediv__(self,other) if __future__.division is in effect.
self //= other __ifloordiv__(self, other)
self %= other __imod__(self, other)
self **= other __ipow__(self, other)
self &= other __iand__(self, other)
self ^= other __ixor__(self, other)
self |= other __ior__(self, other)
self <<= other __ilshift__(self, other)
self >>= other __irshift__(self, other)

Conversions
built-in function Special method
int(self) __int__(self)
long(self) __long__(self)
float(self) __float__(self)
complex(self) __complex__(self)
oct(self) __oct__(self)
hex(self) __hex__(self)
coerce(self, other) __coerce__(self, other)
Right-hand-side equivalents for all binary operators exist; they are called when class instance is on r-h-s of operator:
  • a + 3  calls __add__(a, 3)
  • 3 + a  calls __radd__(a, 3)

Special operations for containers
Operation Special method Notes
All sequences and maps :
len(self) __len__(self) length of object, >= 0. Length 0 == false
self[k] __getitem__(self, k) Get element at indice /key k (indice starts at 0). Or, if k is a slice object, return a slice.
self[k] = value __setitem__(self, k, value) Set element at indice/key/slice k.
del self[k] __delitem__(self, k) Delete element at indice/key/slice k.
elt in self
elt not in self
__contains__(self, elt)
not __contains__(self, elt)
More efficient than std iteration thru sequence.
iter(self) __iter__(self) Returns an iterator on elements (keys for mappings <=> self.iterkeys()). See iterators.
Sequences, general methods, plus:
self[i:j] __getslice__(self, i, j) Deprecated since 2.0, replaced by __getitem__ with a slice object as parameter.
self[i:j] = seq __setslice__(self, i, j,seq) Deprecated since 2.0, replaced by __setitem__ with a slice object as parameter.
del self[i:j] __delslice__(self, i, j) Same as self[i:j] = [] - Deprecated since 2.0, replaced by __delitem__ with a slice object as parameter.
self * n __mul__(self, n) (__repeat__ in the official doc but doesn't work!)
self + other __add__(self, other) (__concat__ in the official doc but doesn't work!)
Mappings, general methods, plus:
hash(self) __hash__(self) hashed value of object self is used for dictionary keys

Special informative state attributes for some types:

Tip: use module inspect to inspect live objects.

Lists & Dictionaries
Attribute Meaning
__methods__ (list, R/O): list of method names of the object Deprecated, use dir() instead
Modules
Attribute Meaning
__doc__ (string/None, R/O): doc string (<=> __dict__['__doc__'])
__name__ (string, R/O): module name (also in __dict__['__name__'])
__dict__ (dict, R/O): module's name space
__file__ (string/undefined, R/O): pathname of .pyc, .pyo or .pyd (undef for modules statically linked to the interpreter)
__path__ (list/undefined, R/W): List of directory paths where to find the package (for packages only).
Classes
Attribute Meaning
__doc__ (string/None, R/W): doc string (<=> __dict__['__doc__'])
__name__ (string, R/W): class name (also in __dict__['__name__'])
__module__ (string, R/W): module name in which the class was defined
__bases__ (tuple, R/W): parent classes
__dict__ (dict, R/W): attributes (class name space)
Instances
Attribute Meaning
__class__ (class, R/W): instance's class
__dict__ (dict, R/W): attributes
User defined functions
Attribute Meaning
__doc__ (string/None, R/W): doc string
__name__ (string, R/O): function name
func_doc (R/W): same as __doc__
func_name (R/O, R/W from 2.4): same as __name__
func_defaults (tuple/None, R/W): default args values if any
func_code (code, R/W): code object representing the compiled function body
func_globals (dict, R/O): ref to dictionary of func global variables
User-defined Methods
Attribute Meaning
__doc__ (string/None, R/O): doc string
__name__ (string, R/O): method name (same as im_func.__name__)
im_class (class, R/O): class defining the method (may be a base class)
im_self (instance/None, R/O): target instance object (None if unbound)
im_func (function, R/O): function object
Built-in Functions & methods
Attribute Meaning
__doc__ (string/None, R/O): doc string
__name__ (string, R/O): function name
__self__ [methods only] target object
__members__ list of attr names: ['__doc__','__name__','__self__']) Deprecated, use dir() instead.
Codes
Attribute Meaning
co_name (string, R/O): function name
co_argcount (int, R/0): number of positional args
co_nlocals (int, R/O): number of local vars (including args)
co_varnames (tuple, R/O): names of local vars (starting with args)
co_code (string, R/O): sequence of bytecode instructions
co_consts (tuple, R/O): literals used by the bytecode, 1st one is function doc (or None)
co_names (tuple, R/O): names used by the bytecode
co_filename (string, R/O): filename from which the code was compiled
co_firstlineno (int, R/O): first line number of the function
co_lnotab (string, R/O): string encoding bytecode offsets to line numbers.
co_stacksize (int, R/O): required stack size (including local vars)
co_flags (int, R/O): flags for the interpreter bit 2 set if fct uses "*arg" syntax, bit 3 set if fct uses '**keywords' syntax
Frames
Attribute Meaning
f_back (frame/None, R/O): previous stack frame (toward the caller)
f_code (code, R/O): code object being executed in this frame
f_locals (dict, R/O): local vars
f_globals (dict, R/O): global vars
f_builtins (dict, R/O): built-in (intrinsic) names
f_restricted (int, R/O): flag indicating whether fct is executed in restricted mode
f_lineno (int, R/O): current line number
f_lasti (int, R/O): precise instruction (index into bytecode)
f_trace (function/None, R/W): debug hook called at start of each source line
f_exc_type (Type/None, R/W): Most recent exception type
f_exc_value (any, R/W): Most recent exception value
f_exc_traceback (traceback/None, R/W): Most recent exception traceback
Tracebacks
Attribute Meaning
tb_next (frame/None, R/O): next level in stack trace (toward the frame where the exception occurred)
tb_frame (frame, R/O): execution frame of the current level
tb_lineno (int, R/O): line number where the exception occured
tb_lasti (int, R/O): precise instruction (index into bytecode)
Slices
Attribute Meaning
start (any/None, R/O): lowerbound, included
stop (any/None, R/O): upperbound, excluded
step (any/None, R/O): step value
Complex numbers
Attribute Meaning
real (float, R/O): real part
imag (float, R/O): imaginary part
xranges
Attribute Meaning
tolist (Built-in method, R/O): ?

Important Modules

sys

System-specific parameters and functions. [Full doc]

Some sys variables
Variable Content
argv The list of command line arguments passed to a Python script. sys.argv[0] is the script name.
builtin_module_names A list of strings giving the names of all modules written in C that are linked into this interpreter.
byteorder Native byte order, either 'big'(-endian) or 'little'(-endian).
check_interval How often to check for thread switches or signals (measured in number of virtual machine instructions)
copyright A string containing the copyright pertaining to the Python interpreter.
exec_prefix
prefix
Root directory where platform-dependent Python files are installed, e.g. 'C:\\Python23', '/usr'.
executable Name of executable binary of the Python interpreter (e.g. 'C:\\Python23\\python.exe', '/usr/bin/python')
exitfunc User can set to a parameterless function. It will get called before interpreter exits. Deprecated since 2.4. Code should be using the existing atexit module
last_type, last_value, last_traceback Set only when an exception not handled and interpreter prints an error. Used by debuggers.
maxint Maximum positive value for integers. Since 2.2 integers and long integers are unified, thus integers have no limit.
maxunicode Largest supported code point for a Unicode character.
modules Dictionary of modules that have already been loaded.
path Search path for external modules. Can be modified by program. sys.path[0] == directory of script currently executed.
platform The current platform, e.g. "sunos5", "win32"
ps1, ps2 Prompts to use in interactive mode, normally ">>>" and "..."
stdin, stdout, stderr File objects used for I/O. One can redirect by assigning a new file object to them (or any object: with a method write(string) for stdout/stderr, or with a method readline() for stdin). __stdin__,__stdout__ and __stderr__ are the default values.
version String containing version info about Python interpreter.
version_info Tuple containing Python version info - (major, minor, micro, level, serial).
winver Version number used to form registry keys on Windows platforms (e.g. '2.2').
Some sys functions
Function Result
displayhook The function used to display the output of commands issued in interactive mode - defaults to the builtin repr(). __displayhook__ is the original value.
excepthook Can be set to a user defined function, to which any uncaught exceptions are passed. __excepthook__ is the original value.
exit(n) Exits with status n (usually 0 means OK). Raises SystemExit exception (hence can be caught and ignored by program)
getrefcount(object) Returns the reference count of the object. Generally 1 higher than you might expect, because of object arg temp reference.
setcheckinterval(interval) Sets the interpreter's thread switching interval (in number of bytecode instructions, default: 10 until 2.2, 100 from 2.3).
settrace(func) Sets a trace function: called before each line of code is exited.
setprofile(func) Sets a profile function for performance profiling.
exc_info() Info on exception currently being handled; this is a tuple (exc_type, exc_value, exc_traceback). Warning: assigning the traceback return value to a local variable in a function handling an exception will cause a circular reference.
setdefaultencoding(encoding) Change default Unicode encoding - defaults to 7-bit ASCII.
getrecursionlimit() Retrieve maximum recursion depth.
setrecursionlimit() Set maximum recursion depth (default 1000).

os

Miscellaneous operating system interfaces. [Full doc]

"synonym" for whatever OS-specific module (nt, mac, posix...) is proper for current environment. This module uses posix whenever possible.
(see also M.A. Lemburg's utility platform.py (now included in 2.3+)

Some os variables
Variable Meaning
name name of O/S-specific module (e.g. "posix", "mac", "nt")
path O/S-specific module for path manipulations.
On Unix, os.path.split() <=> posixpath.split()
curdir string used to represent current directory (eg '.')
pardir string used to represent parent directory (eg '..')
sep string used to separate directories ('/' or '\'). Tip: Use os.path.join() to build portable paths.
altsep Alternate separator if applicable (None otherwise)
pathsep character used to separate search path components (as in $PATH), eg. ';' for windows.
linesep line separator as used in text files, ie '\n' on Unix, '\r\n' on Dos/Win, '\r' on Mac.
Some os functions
Function Result
makedirs(path[, mode=0777]) Recursive directory creation (create required intermediary dirs); os.error if fails.
removedirs(path) Recursive directory delete (delete intermediary empty dirs); fails (os.error) if the directories are not empty.
renames(old, new) Recursive directory or file renaming; os.error if fails.
urandom(n) Returns a string containing n bytes of random data.

posix

Posix OS interfaces. [Full doc]
Do not import this module directly, import os instead ! (see also module: shutil for file copy & remove functions)

posix Variables
Variable Meaning
environ dictionary of environment variables, e.g. posix.environ['HOME'].
error exception raised on POSIX-related error.
Corresponding value is tuple of errno code and perror() string.
Some posix functions
Function Result
chdir(path) Changes current directory to path.
chmod(path, mode) Changes the mode of path to the numeric mode
close(fd) Closes file descriptor fd opened with posix.open.
_exit(n) Immediate exit, with no cleanups, no SystemExit, etc... Should use this to exit a child process.
execv(p, args) "Become" executable p with args args
getcwd() Returns a string representing the current working directory.
getcwdu() Returns a Unicode string representing the current working directory.
getpid() Returns the current process id.
getsid() Calls the system call getsid() [Unix].
fork() Like C's fork(). Returns 0 to child, child pid to parent [Not on Windows].
kill(pid, signal) Like C's kill [Not on Windows].
listdir(path) Lists (base)names of entries in directory path, excluding '.' and '..'. If path is a Unicode string, so will be the returned strings.
lseek(fd, pos, how) Sets current position in file fd to position pos, expressed as an offset relative to beginning of file (how=0), to current position (how=1), or to end of file (how=2).
mkdir(path[, mode]) Creates a directory named path with numeric mode (default 0777).
open(file, flags, mode) Like C's open(). Returns file descriptor. Use file object functions rather than this low level ones.
pipe() Creates a pipe. Returns pair of file descriptors (r, w) [Not on Windows].
popen(command, mode='r', bufSize=0) Opens a pipe to or from command. Result is a file object to read to or write from, as indicated by mode being 'r' or 'w'. Use it to catch a command output ('r' mode), or to feed it ('w' mode).
remove(path) See unlink.
rename(old, new) Renames/moves the file or directory old to new. [error if target name already exists]
renames(old, new) Recursive directory or file renaming function. Works like rename(), except creation of any intermediate directories needed to make the new pathname good is attempted first. After the rename, directories corresponding to rightmost path segments of the old name will be pruned away using removedirs().
rmdir(path) Removes the empty directory path
read(fd, n) Reads n bytes from file descriptor fd and return as string.
stat(path) Returns st_mode, st_ino, st_dev, st_nlink, st_uid,st_gid, st_size, st_atime, st_mtime, st_ctime. [st_ino, st_uid, st_gid are dummy on Windows]
system(command) Executes string command in a subshell. Returns exit status of subshell (usually 0 means OK). Since 2.4 use subprocess.call() instead.
times() Returns accumulated CPU times in sec (user, system, children's user, children's sys, elapsed real time) [3 last not on Windows].
unlink(path) Unlinks ("deletes") the file (not dir!) path. Same as: remove.
utime(path, (aTime, mTime)) Sets the access & modified time of the file to the given tuple of values.
wait() Waits for child process completion. Returns tuple of pid, exit_status [Not on Windows].
waitpid(pid, options) Waits for process pid to complete. Returns tuple of pid, exit_status [Not on Windows].
walk(top[, topdown=True [, onerror=None]]) Generates a list of file names in a directory tree, by walking the tree either top down or bottom up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames) - more info here. See also os.path.walk().
write(fd, str) Writes str to file fd. Returns nb of bytes written.

posixpath

Posix pathname operations.
Do not import this module directly, import os instead and refer to this module as os.path. (e.g. os.path.exists(p))!

Some posixpath functions
Function Result
abspath(p) Returns absolute path for path p, taking current working dir in account.
commonprefix(list) Returns the longuest path prefix (taken character-by-character) that is a prefix of all paths in list (or '' if list empty).
dirname/basename(p) directory and name parts of the path p. See also split.
exists(p) True if string p is an existing path (file or directory). See also lexists.
expanduser(p) Returns string that is (a copy of) p with "~" expansion done.
expandvars(p) Returns string that is (a copy of) p with environment vars expanded. [Windows: case significant; must use Unix: $var notation, not %var%]
getmtime(filepath) Returns last modification time of filepath (integer nb of seconds since epoch).
getatime(filepath) Returns last access time of filepath (integer nb of seconds since epoch).
getsize(filepath) Returns the size in bytes of filepath. os.error if file inexistent or inaccessible.
isabs(p) True if string p is an absolute path.
isdir(p) True if string p is a directory.
islink(p) True if string p is a symbolic link.
ismount(p) True if string p is a mount point [true for all dirs on Windows].
join(p[,q[,...]]) Joins one or more path components intelligently.
lexists(path) True if the file specified by path exists, whether or not it's a symbolic link (unlike exists).
split(p) Splits p into (head, tail) where tail is last pathname component and head is everything leading up to that. <=> (dirname(p), basename(p))
splitdrive(p) Splits path p in a pair ('drive:', tail) [Windows]
splitext(p) Splits into (root, ext) where last comp of root contains no periods and ext is empty or starts with a period.
walk(p, visit, arg) Calls the function visit with arguments (arg, dirname, names) for each directory recursively in the directory tree rooted at p (including p itself if it's a dir). The argument dirname specifies the visited directory, the argument names lists the files in the directory. The visit function may modify names to influence the set of directories visited below dirname, e.g. to avoid visiting certain parts of the tree. See also os.walk() for an alternative.

shutil

High-level file operations (copying, deleting). [Full doc]

Main shutil functions
Function Result
copy(src, dest) Copies the contents of file src to file dest, retaining file permissions.
copytree(src, dest[, symlinks]) Recursively copies an entire directory tree rooted at src into dest (which should not already exist). If symlinks is true, links in src are kept as such in dest.
move(src, dest) Recursively moves a file or directory to a new location.
rmtree(path[, ignore_errors[, onerror]]) Deletes an entire directory tree, ignoring errors if ignore_errors is true, or calling onerror(func, path, sys.exc_info()) if supplied, with arguments func (faulty function), and path (concerned file).
(and also: copyfile, copymode, copystat, copy2)

time

Time access and conversions. [Full doc]
(see also module mxDateTime if you need a more sophisticated date/time management)

Variables
Variable Meaning
altzone Signed offset of local DST timezone in sec west of the 0th meridian.
daylight Non zero if a DST timezone is specified.
Some functions
Function Result
time() Returns a float representing UTC time in seconds since the epoch.
gmtime(secs), localtime(secs) Returns a tuple representing time : (year aaaa, month(1-12), day(1-31), hour(0-23), minute(0-59), second(0-59), weekday(0-6, 0 is monday), Julian day(1-366), daylight flag(-1,0 or 1)).
asctime(timeTuple), 24-character string of the following form: 'Sun Jun 20 23:21:05 1993'.
strftime(format, timeTuple) Returns a formated string representing time. See format in table below.
mktime(tuple) Inverse of localtime(). Returns a float.
strptime(string[, format]) Parses a formated string representing time, return tuple as in gmtime().
sleep(secs) Suspends execution for secs seconds. secs can be a float.
and also: clock, ctime.

Formatting in strftime()
Directive Meaning
%a Locale's abbreviated weekday name.
%A Locale's full weekday name.
%b Locale's abbreviated month name.
%B Locale's full month name.
%c Locale's appropriate date and time representation.
%d Day of the month as a decimal number [01,31].
%H Hour (24-hour clock) as a decimal number [00,23].
%I Hour (12-hour clock) as a decimal number [01,12].
%j Day of the year as a decimal number [001,366].
%m Month as a decimal number [01,12].
%M Minute as a decimal number [00,59].
%p Locale's equivalent of either AM or PM.
%S Second as a decimal number [00,61]. Yes, 61 !
%U Week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday are considered to be in week 0.
%w Weekday as a decimal number [0(Sunday),6].
%W Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday are considered to be in week 0.
%x Locale's appropriate date representation.
%X Locale's appropriate time representation.
%y Year without century as a decimal number [00,99].
%Y Year with century as a decimal number.
%Z Time zone name (or by no characters if no time zone exists).
%% A literal "%" character.

string

Common string operations. [Full doc]
As of Python 2.0, much (though not all) of the functionality provided by the string module have been superseded by built-in string methods - see Operations on strings for details.

Some string variables
Variable Meaning
digits The string '0123456789'.
hexdigits, octdigits Legal hexadecimal & octal digits.
letters, uppercase, lowercase, whitespace Strings containing the appropriate characters.
ascii_letters, ascii_lowercase, ascii_uppercase Same, taking the current locale in account.
index_error Exception raised by index() if substring not found.
Some string functions
Function Result
expandtabs(s, tabSize) Returns a copy of string s with tabs expanded.
find/rfind(s, sub[, start=0[, end=0]) Returns the lowest/highest index in s where the substring sub is found such that sub is wholly contained in s[start:end]. Return -1 if sub not found.
ljust/rjust/center(s, width[, fillChar=' ']) Returns a copy of string s; left/right justified/centered in a field of given width, padded with spaces or the given character. s is never truncated.
lower/upper(s) Returns a string that is (a copy of) s in lowercase/uppercase.
split(s[, sep=whitespace[, maxsplit=0]]) Returns a list containing the words of the string s, using the string sep as a separator.
rsplit(s[, sep=whitespace[, maxsplit=0]]) Same as split above but starts splitting from the end of string, e.g. 'A,B,C'.split(',', 1) == ['A', 'B,C'] but 'A,B,C'.rsplit(',', 1) == ['A,B', 'C']
join(words[, sep=' ']) Concatenates a list or tuple of words with intervening separators; inverse of split.
replace(s, old, new[, maxsplit=0] Returns a copy of string s with all occurrences of substring old replaced by new. Limits to maxsplit first substitutions if specified.
strip(s[, chars=None]) Returns a string that is (a copy of) s without leading and trailing chars (default: whitespace). Also: lstrip, rstrip.

re (sre)

Regular expression operations. [Full doc]

Handles Unicode strings. Implemented in new module sre, re now a mere front-end for compatibility.
Patterns are specified as strings. Tip: Use raw strings (e.g. r'\w*') to literalize backslashes.

Regular expression syntax
Form Description
. Matches any character (including newline if DOTALL flag specified).
^ Matches start of the string (of every line in MULTILINE mode).
$ Matches end of the string (of every line in MULTILINE mode).
* 0 or more of preceding regular expression (as many as possible).
+ 1 or more of preceding regular expression (as many as possible).
? 0 or 1 occurrence of preceding regular expression.
*?, +?, ?? Same as *, + and ? but matches as few characters as possible.
{m,n} Matches from m to n repetitions of preceding RE.
{m,n}? Idem, attempting to match as few repetitions as possible.
[ ] Defines character set: e.g. '[a-zA-Z]' to match all letters (see also \w \S).
[^ ] Defines complemented character set: matches if char is NOT in set.
\ Escapes special chars '*?+&$|()' and introduces special sequences (see below). Due to Python string rules, write as '\\' or r'\' in the pattern string.
\\ Matches a litteral '\'; due to Python string rules, write as '\\\\' in pattern string, or better using raw string: r'\\'.
| Specifies alternative: 'foo|bar' matches 'foo' or 'bar'.
(...) Matches any RE inside (), and delimits a group.
(?:...) Idem but doesn't delimit a group (non capturing parenthesis).
(?P<name>...) Matches any RE inside (), and delimits a named group, (e.g. r'(?P<id>[a-zA-Z_]\w*)' defines a group named id).
(?P=name) Matches whatever text was matched by the earlier group named name.
(?=...) Matches if ... matches next, but doesn't consume any of the string e.g. 'Isaac (?=Asimov)' matches 'Isaac' only if followed by 'Asimov'.
(?!...) Matches if ... doesn't match next. Negative of (?=...).
(?<=...) Matches if the current position in the string is preceded by a match for ... that ends at the current position. This is called a positive lookbehind assertion.
(?<!...) Matches if the current position in the string is not preceded by a match for .... This is called a negative lookbehind assertion.
(?(group)A|B) [2.4+] group is either a numeric group ID or a group name defined with (?Pgroup...) earlier in the expression. If the specified group matched, the regular expression pattern A will be tested against the string; if the group didn't match, the pattern B will be used instead.
(?#...) A comment; ignored.
(?letters) letters is one or more of 'i','L', 'm', 's', 'u', 'x'. Sets the corresponding flags (re.I, re.L, re.M, re.S, re.U, re.X) for the entire RE. See the compile() function for equivalent flags.
Special sequences
Sequence Description
number Matches content of the group of the same number; groups are numbered starting from 1.
\A Matches only at the start of the string.
\b Empty str at beginning or end of word: '\bis\b' matches 'is', but not 'his'.
\B Empty str NOT at beginning or end of word.
\d Any decimal digit (<=> [0-9]).
\D Any non-decimal digit char (<=> [^0-9]).
\s Any whitespace char (<=> [ \t\n\r\f\v]).
\S Any non-whitespace char (<=> [^ \t\n\r\f\v]).
\w Any alphaNumeric char (depends on LOCALE flag).
\W Any non-alphaNumeric char (depends on LOCALE flag).
\Z Matches only at the end of the string.
Variables
Variable Meaning
error Exception when pattern string isn't a valid regexp.
Functions
Function Result
compile(pattern[,flags=0]) Compiles a RE pattern string into a regular expression object.
Flags (combinable by |):
I or IGNORECASE <=> (?i)
case insensitive matching
L or LOCALE <=> (?L)
make \w, \W, \b, \B dependent on the current locale
M or MULTILINE <=> (?m)
matches every new line and not only start/end of the whole string
S or DOTALL <=> (?s)
'.' matches ALL chars, including newline
U or UNICODE <=> (?u)
Make \w, \W, \b, and \B dependent on the Unicode character properties database.
X or VERBOSE <=> (?x)
Ignores whitespace outside character sets
escape(string) Returns (a copy of) string with all non-alphanumerics backslashed.
match(pattern, string[, flags]) If 0 or more chars at beginning of string matches the RE pattern string, returns a corresponding MatchObject instance, or None if no match.
search(pattern, string[, flags]) Scans thru string for a location matching pattern, returns a corresponding MatchObject instance, or None if no match.
split(pattern, string[, maxsplit=0]) Splits string by occurrences of pattern. If capturing () are used in pattern, then occurrences of patterns or subpatterns are also returned.
findall(pattern, string) Returns a list of non-overlapping matches in pattern, either a list of groups or a list of tuples if the pattern has more than 1 group.
sub(pattern, repl, string[, count=0]) Returns string obtained by replacing the (count first) leftmost non-overlapping occurrences of pattern (a string or a RE object) in string by repl; repl can be a string or a function called with a single MatchObj arg, which must return the replacement string.
subn(pattern, repl, string[, count=0]) Same as sub(), but returns a tuple (newString, numberOfSubsMade).

Regular Expression Objects

RE objects are returned by the compile function.

re object attributes
Attribute Description
flags Flags arg used when RE obj was compiled, or 0 if none provided.
groupindex Dictionary of {group name: group number} in pattern.
pattern Pattern string from which RE obj was compiled.
re object methods
Method Result
match(string[, pos][, endpos]) If zero or more characters at the beginning of string match this regular expression, returns a corresponding MatchObject instance. Returns None if the string does not match the pattern; note that this is different from a zero-length match.
The optional second parameter pos gives an index in the string where the search is to start; it defaults to 0. This is not completely equivalent to slicing the string; the '' pattern character matches at the real beginning of the string and at positions just after a newline, but not necessarily at the index where the search is to start.
The optional parameter endpos limits how far the string will be searched; it will be as if the string is endpos characters long, so only the characters from pos to endpos will be searched for a match.
search(string[, pos][, endpos]) Scans through string looking for a location where this regular expression produces a match, and returns a corresponding MatchObject instance. Returns None if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string.
The optional pos and endpos parameters have the same meaning as for the match() method.
split(string[, maxsplit=0]) Identical to the split() function, using the compiled pattern.
findall(string) Identical to the findall() function, using the compiled pattern.
sub(repl, string[, count=0]) Identical to the sub() function, using the compiled pattern.
subn(repl, string[, count=0]) Identical to the subn() function, using the compiled pattern.

Match Objects

Match objects are returned by the match & search functions.

Match object attributes
Attribute Description
pos Value of pos passed to search or match functions; index into string at which RE engine started search.
endpos Value of endpos passed to search or match functions; index into string beyond which RE engine won't go.
re RE object whose match or search fct produced this MatchObj instance.
string String passed to match() or search().
Match object functions
Function Result
group([g1, g2, ...]) Returns one or more groups of the match. If one arg, result is a string; if multiple args, result is a tuple with one item per arg. If gi is 0, returns value is entire matching string; if 1 <= gi <= 99, return string matching group #gi (or None if no such group); gi may also be a group name.
groups() Returns a tuple of all groups of the match; groups not participating to the match have a value of None. Returns a string instead of tuple if len(tuple)== 1.
start(group), end(group) Returns indices of start & end of substring matched by group (or None if group exists but didn't contribute to the match).
span(group) Returns the 2-tuple (start(group), end(group)); can be (None, None) if group didn't contibute to the match.

math

For intensive number crunching, see also Numerical Python and the Python and Scientific computing page. [Full doc]

Constants
Name Value
pi 3.1415926535897931
e 2.7182818284590451
Functions
Name Result
acos(x) Returns the arc cosine (measured in radians) of x.
asin(x) Returns the arc sine (measured in radians) of x.
atan(x) Returns the arc tangent (measured in radians) of x.
atan2(y, x) Returns the arc tangent (measured in radians) of y/x. The result is between -pi and pi. Unlike atan(y/x), the signs of both x and y are considered.
ceil(x) Returns the ceiling of x as a float. This is the smallest integral value >= x.
cos(x) Returns the cosine of x (measured in radians).
cosh(x) Returns the hyperbolic cosine of x.
degrees(x) Converts angle x from radians to degrees.
exp(x) Returns e raised to the power of x.
fabs(x) Returns the absolute value of the float x.
floor(x) Returns the floor of x as a float. This is the largest integral value <= x.
fmod(x, y) Returns fmod(x, y), according to platform C. x % y may differ.
frexp(x) Returns the mantissa and exponent of x, as pair (m, e). m is a float and e is an int, such that x = m * 2.**e. If x is 0, m and e are both 0. Else 0.5 <= abs(m) < 1.0.
hypot(x, y) Returns the Euclidean distance sqrt(x*x + y*y).
ldexp(x, i) x * (2**i)
log(x[, base]) Returns the logarithm of x to the given base. If the base is not specified, returns the natural logarithm (base e) of x.
log10(x) Returns the base 10 logarithm of x.
modf(x) Returns the fractional and integer parts of x. Both results carry the sign of x. The integer part is returned as a float.
pow(x, y) Returns x**y (x to the power of y). Note that for y=2, it is more efficient to use x*x.
radians(x) Converts angle x from degrees to radians.
sin(x) Returns the sine (measured in radians) of x.
sinh(x) Returns the hyperbolic sine of x.
sqrt(x) Returns the square root of x.
tan(x) Returns the tangent (measured in radians) of x.
tanh(x) Returns the hyperbolic tangent of x.

getopt

Parser for command line options. [Full doc]

This was the standard parser until Python 2.3, now superseded by optparse.
[see also: Richard Gruet's simple parser getargs.py (shameless self promotion)]

Functions:
getopt(list, optstr)    -- Similar to C. <optstr> is option letters to look for. 
Put ':' after letter if option takes arg. E.g.
# invocation was "python test.py -c hi -a arg1 arg2"
opts, args = getopt.getopt(sys.argv[1:], 'ab:c:')
# opts would be
[('-c', 'hi'), ('-a', '')]
# args would be
['arg1', 'arg2']

List of modules and packages in base distribution

Built-ins and content of python Lib directory. The subdirectory Lib/site-packages contains platform-specific packages and modules.
[Python NT distribution, may be slightly different in other distributions]

Standard library modules
Operation Result
aifc Stuff to parse AIFF-C and AIFF files.
anydbm Generic interface to all dbm clones. (dbhash, gdbm, dbm, dumbdbm).
asynchat A class supporting chat-style (command/response) protocols.
asyncore Basic infrastructure for asynchronous socket service clients and servers.
atexit Register functions to be called at exit of Python interpreter.
audiodev Classes for manipulating audio devices (currently only for Sun and SGI).
base64 Conversions to/from base64 transport encoding as per RFC-1521.
BaseHTTPServer HTTP server base class
Bastion "Bastionification" utility (control access to instance vars).
bdb A generic Python debugger base class.
bsddb (Optional) improved BSD database interface [package].
binhex Macintosh binhex compression/decompression.
bisect Bisection algorithms.
bz2 BZ2 compression.
calendar Calendar printing functions.
cgi Wraps the WWW Forms Common Gateway Interface (CGI).
CGIHTTPServer CGI-savvy HTTP Server.
cmd A generic class to build line-oriented command interpreters.
cmp Efficiently compare files, boolean outcome only.
cmpcache Same, but caches 'stat' results for speed.
code Utilities needed to emulate Python's interactive interpreter.
codecs Lookup existing Unicode encodings and register new ones.
codeop Utilities to compile possibly incomplete Python source code.
collections high-performance container datatypes. Currently, the only datatype is a double-ended queue.
colorsys Conversion functions between RGB and other color systems.
commands Execute shell commands via os.popen [Unix only].
compileall Force "compilation" of all .py files in a directory.
ConfigParser Configuration file parser (much like windows .ini files).
Cookie HTTP state (cookies) management.
copy Generic shallow and deep copying operations.
copy_reg Helper to provide extensibility for modules pickle/cPickle.
csv Tools to read comma-separated files (of variations thereof).
datetime Improved date/time types (date, time, datetime, timedelta).
dbhash (g)dbm-compatible interface to bsdhash.hashopen.
decimal Decimal floating point arithmetic.
difflib Tool for comparing sequences, and computing the changes required to convert one into another.
dircache Sorted list of files in a dir, using a cache.
dircmp Defines a class to build directory diff tools on.
dis Bytecode disassembler.
distutils Package installation system.
distutils.command.register Registers a module in the Python package index (PyPI). This command plugin adds the register command to distutil scripts.
distutils.debug  
distutils.emxccompiler  
distutils.log  
doctest Unit testing framework based on running examples embedded in docstrings.
DocXMLRPCServer Creation of self-documenting XML-RPC servers, using pydoc to create HTML API doc on the fly.
dospath Common operations on DOS pathnames.
dumbdbm A dumb and slow but simple dbm clone.
dump Print python code that reconstructs a variable.
dummy_thread  
dummy_threading Helpers to make it easier to write code that uses threads where supported, but still runs on Python versions without thread support. The dummy modules simply run the threads sequentially.
email A package for parsing, handling, and generating email messages. New version 3.0 dropped various deprecated APIs and removes support for Python versions earlier than 2.3.
encodings New codecs: idna (IDNA strings), koi8_u (Ukranian), palmos (PalmOS 3.5), punycode (Punycode IDNA codec), string_escape (Python string escape codec: replaces non-printable chars w/ Python-style string escapes). New codecs in 2.4: HP Roman8, ISO_8859-11, ISO_8859-16, PCTP-154, TIS-620; Chinese, Japanese and Korean codecs.
exceptions Class based built-in exception hierarchy.
filecmp File and directory comparison.
fileinput Helper class to quickly write a loop over all standard input files.
find Find files directory hierarchy matching a pattern.
fnmatch Filename matching with shell patterns.
formatter Generic output formatting.
fpformat General floating point formatting functions.
ftplib An FTP client class. Based on RFC 959.
gc Perform garbage collection, obtain GC debug stats, and tune GC parameters.
getopt Standard command line processing. See also optparse.
getpass Utilities to get a password and/or the current user name.
gettext Internationalization and localization support.
glob Filename "globbing" utility.
gopherlib Gopher protocol client interface.
grep 'grep' utilities.
gzip Read & write gzipped files.
heapq Heap queue (priority queue) helpers.
hmac HMAC (Keyed-Hashing for Message Authentication).
hotshot.stones Helper to run the pystone benchmark under the Hotshot profiler.
htmlentitydefs HTML character entity references.
htmllib HTML2 parsing utilities
HTMLParser Simple HTML and XHTML parser.
httplib HTTP1 client class.
idlelib (package) Support library for the IDLE development environment.
ihooks Hooks into the "import" mechanism.
imaplib IMAP4 client.Based on RFC 2060.
imghdr Recognizing image files based on their first few bytes.
imputil Provides a way of writing customized import hooks.
inspect Get information about live Python objects.
itertools Tools to work with iterators and lazy sequences.
keyword List of Python keywords.
knee A Python re-implementation of hierarchical module import.
linecache Cache lines from files.
linuxaudiodev Linux /dev/audio support. Replaced by ossaudiodev(Linux).
locale Support for number formatting using the current locale settings.
logging (package) Tools for structured logging in log4j style.
macpath Pathname (or related) operations for the Macintosh [Mac].
macurl2path Mac specific module for conversion between pathnames and URLs [Mac].
mailbox Classes to handle Unix style, MMDF style, and MH style mailboxes.
mailcap Mailcap file handling (RFC 1524).
marshal Internal Python object serialization.
markupbase Shared support for scanning document type declarations in HTML and XHTML.
mhlib MH (mailbox) interface.
mimetools Various tools used by MIME-reading or MIME-writing programs.
mimetypes Guess the MIME type of a file.
MimeWriter Generic MIME writer. Deprecated since release 2.3. Use the email package instead.
mimify Mimification and unmimification of mail messages.
mmap Interface to memory-mapped files - they behave like mutable strings.
modulefinder Tools to find what modules a given Python program uses, without actually running the program.
multifile A readline()-style interface to the parts of a multipart message.
mutex Mutual exclusion -- for use with module sched. See also std module threading, and glock.
netrc Parses and encapsulates the netrc file format.
nntplib An NNTP client class. Based on RFC 977.
ntpath Common operations on Windows pathnames.
nturl2path Convert a NT pathname to a file URL and vice versa.
olddifflib Old version of difflib (helpers for computing deltas between objects)?
operator Standard operators as functions
optparse Improved command-line option parsing library (see also getopt).
os OS routines for Mac, DOS, NT, or Posix depending on what system we're on.
os2emxpath os.path support for OS/2 EMX.
packmail Create a self-unpacking shell archive.
pdb A Python debugger.
pickle Pickling (save and restore) of Python objects (a faster C implementation exists in built-in module: cPickle).
pickletools Tools to analyze and disassemble pickles.
pipes Conversion pipeline templates.
pkgutil Tools to extend the module search path for a given package.
platform Get info about the underlying platform.
poly Polynomials.
popen2 Spawn a command with pipes to its stdin, stdout, and optionally stderr. Superseded by module subprocess since 2.4
poplib A POP3 client class.
posixfile Extended file operations available in POSIX.
posixpath Common operations on POSIX pathnames.
pprint Support to pretty-print lists, tuples, & dictionaries recursively.
pre Support for regular expressions (RE) - see re.
profile Class for profiling python code.
pstats Class for printing reports on profiled python code.
pty Pseudo terminal utilities.
py_compile Routine to "compile" a .py file to a .pyc file.
pyclbr Parse a Python file and retrieve classes and methods.
pydoc Generate Python documentation in HTML or text for interactive use.
pyexpat Interface to the Expat XML parser.
PyUnit Unit test framework inspired by JUnit. See unittest.
Queue A multi-producer, multi-consumer queue.
quopri Conversions to/from quoted-printable transport encoding as per RFC 1521.
rand Don't use unless you want compatibility with C's rand().
random Random variable generators.
re Regular Expressions.
readline GNU readline interface [Unix].
reconvert Convert old ("regex") regular expressions to new syntax ("re").
regex_syntax Flags for regex.set_syntax().
regexp Backward compatibility for module "regexp" using "regex".
regsub Regexp-based split and replace using the obsolete regex module.
repr Redo repr() but with limits on most sizes.
rexec Restricted execution facilities ("safe" exec, eval, etc).
rfc822 Parse RFC-8222 mail headers.
rlcompleter Word completion for GNU readline 2.0.
robotparser Parse robot.txt files, useful for web spiders.
sched A generally useful event scheduler class.
sets A Set datatype implementation based on dictionaries (see Sets).
sgmllib A parser for SGML, using the derived class as a static DTD.
shelve Manage shelves of pickled objects.
shlex Lexical analyzer class for simple shell-like syntaxes.
shutil Utility functions for copying files and directory trees.
SimpleHTTPServer Simple HTTP Server.
SimpleXMLRPCServer Simple XML-RPC Server
site Append module search paths for third-party packages to sys.path.
smtpd An RFC 2821 smtp proxy.
smtplib SMTP/ESMTP client class.
sndhdr Several routines that help recognizing sound.
socket Socket operations and some related functions. Now supports timeouts thru function settimeout(t). Also supports SSL on Windows.
SocketServer Generic socket server classes.
sre Support for regular expressions (RE). See re.
stat Constants/functions for interpreting results of os.
statcache Maintain a cache of stat() information on files.
statvfs Constants for interpreting statvfs struct as returned by os.statvfs() and os.fstatvfs() (if they exist).
string A collection of string operations (see Strings).
stringprep Normalization and manipulation of Unicode strings.
StringIO File-like objects that read/write a string buffer (a faster C implementation exists in built-in module: cStringIO).
subprocess Subprocess management. Replacement for os.system, os.spawn*, os.popen*, popen2.* [PEP324]
sunau Stuff to parse Sun and NeXT audio files.
sunaudio Interpret sun audio headers.
symbol Non-terminal symbols of Python grammar (from "graminit.h").
symtable Interface to the compiler's internal symbol tables.
tabnanny Check Python source for ambiguous indentation.
tarfile Tools to read and create TAR archives.
telnetlib TELNET client class. Based on RFC 854.
tempfile Temporary files and filenames.
textwrap Tools to wrap paragraphs of text.
threading Proposed new threading module, emulating a subset of Java's threading model.
threading_api (doc of the threading module).
timeit Benchmark tool.
toaiff Convert "arbitrary" sound files to AIFF (Apple and SGI's audio format).
token Token constants (from "token.h").
tokenize Tokenizer for Python source.
traceback Extract, format and print information about Python stack traces.
trace Tools to trace execution of a function or program.
tty Terminal utilities [Unix].
turtle LogoMation-like turtle graphics.
types Define names for all type symbols in the std interpreter.
tzparse Parse a timezone specification.
unicodedata Interface to unicode properties.
unittest Python unit testing framework, based on Erich Gamma's and Kent Beck's JUnit.
urllib Open an arbitrary URL.
urllib2 An extensible library for opening URLs using a variety of protocols.
urlparse Parse (absolute and relative) URLs.
user Hook to allow user-specified customization code to run.
UserDict A wrapper to allow subclassing of built-in dict class (useless with new-style classes. Since Python 2.2, dict is subclassable).
UserList A wrapper to allow subclassing of built-in list class (useless with new-style classes. Since Python 2.2, list is subclassable)
UserString A wrapper to allow subclassing of built-in string class (useless with new-style classes. Since Python 2.2, str is subclassable).
util some useful functions that don't fit elsewhere !!
uu Implementation of the UUencode and UUdecode functions.
warnings Python part of the warnings subsystem. Issue warnings, and filter unwanted warnings.
wave Stuff to parse WAVE files.
weakref Weak reference support for Python. Also allows the creation of proxy objects.
webbrowser Platform independent URL launcher.
whatsound Several routines that help recognizing sound files.
whichdb Guess which db package to use to open a db file.
whrandom Wichmann-Hill random number generator (obsolete, use random instead).
xdrlib Implements (a subset of) Sun XDR (eXternal Data Representation).
xmllib A parser for XML, using the derived class as static DTD.
xml.dom Classes for processing XML using the DOM (Document Object Model). 2.3: New modules expatbuilder, minicompat, NodeFilter, xmlbuilder.
xml.sax Classes for processing XML using the SAX API.
xmlrpclib An XML-RPC client interface for Python.
xreadlines Provides a sequence-like object for reading a file line-by-line without reading the entire file into memory. Deprecated since release 2.3. Use for line in file instead. Removed since 2.4
zipfile Read & write PK zipped files.
zipimport ZIP archive importer.
zmod Demonstration of abstruse mathematical concepts.

Workspace exploration and idiom hints

dir(object)                        list valid attributes of object (which can be a module, type or class object)
dir() list names in current local symbol table.
if __name__ == '__main__': main() invoke main() if running as script map(None, lst1, lst2, ...) merge lists; see also zip(lst1, lst2, ...)
b = a[:] create a copy b of sequence a
b = list(a) If a is a list, create a copy of it.
_ (underscore) in interactive mode, refers to the last value printed.

Python Mode for Emacs

Emacs goodies available here.
(The following has not been revised, probably not up to date - any contribution welcome -)


Type C-c ? when in python-mode for extensive help.
INDENTATION
Primarily for entering new code:
TAB indent line appropriately
LFD insert newline, then indent
DEL reduce indentation, or delete single character
Primarily for reindenting existing code:
C-c : guess py-indent-offset from file content; change locally
C-u C-c : ditto, but change globally
C-c TAB reindent region to match its context
C-c < shift region left by py-indent-offset
C-c > shift region right by py-indent-offset
MARKING & MANIPULATING REGIONS OF CODE
C-c C-b mark block of lines
M-C-h mark smallest enclosing def
C-u M-C-h mark smallest enclosing class
C-c # comment out region of code
C-u C-c # uncomment region of code
MOVING POINT
C-c C-p move to statement preceding point
C-c C-n move to statement following point
C-c C-u move up to start of current block
M-C-a move to start of def
C-u M-C-a move to start of class
M-C-e move to end of def
C-u M-C-e move to end of class
EXECUTING PYTHON CODE
C-c C-c sends the entire buffer to the Python interpreter
C-c | sends the current region
C-c ! starts a Python interpreter window; this will be used by
subsequent C-c C-c or C-c | commands
VARIABLES
py-indent-offset indentation increment
py-block-comment-prefix comment string used by py-comment-region
py-python-command shell command to invoke Python interpreter
py-scroll-process-buffer t means always scroll Python process buffer
py-temp-directory directory used for temp files (if needed)
py-beep-if-tab-change ring the bell if tab-width is changed