GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing docs.python.org — 11. 標準ライブラリをひとめぐり --- その II 11. 標準ライブラリをひとめぐり --- その II¶ツアーの第2部では、プロフェッショナルプログラミングを支えるもっと高度なモジュールをカバーします。ここで挙げるモジュールは、小さなスクリプトの開発ではほとんど使いません。 11.1. 出力のフォーマット¶
>>> import reprlib >>> reprlib.repr(set('supercalifragilisticexpialidocious')) "{'a', 'c', 'd', 'e', 'f', 'g', ...}"
>>> import pprint >>> t = [[[['black', 'cyan'], 'white', ['green', 'red']], [['magenta', ... 'yellow'], 'blue']]] ... >>> pprint.pprint(t, width=30) [[[['black', 'cyan'], 'white', ['green', 'red']], [['magenta', 'yellow'], 'blue']]]
>>> import textwrap >>> doc = """The wrap() method is just like fill() except that it returns ... a list of strings instead of one big string with newlines to separate ... the wrapped lines.""" ... >>> print(textwrap.fill(doc, width=40)) The wrap() method is just like fill() except that it returns a list of strings instead of one big string with newlines to separate the wrapped lines.
>>> import locale >>> locale.setlocale(locale.LC_ALL, 'English_United States.1252') 'English_United States.1252' >>> conv = locale.localeconv() # 表記規則のマッピングを取得する >>> x = 1234567.8 >>> locale.format_string("%d", x, grouping=True) '1,234,567' >>> locale.format_string("%s%.*f", (conv['currency_symbol'], ... conv['frac_digits'], x), grouping=True) '$1,234,567.80' 11.2. 文字列テンプレート¶
テンプレートでは、 >>> from string import Template >>> t = Template('${village}folk send $$10 to $cause.') >>> t.substitute(village='Nottingham', cause='the ditch fund') 'Nottinghamfolk send $10 to the ditch fund.'
>>> t = Template('Return the $item to $owner.') >>> d = dict(item='unladen swallow') >>> t.substitute(d) Traceback (most recent call last): ... KeyError: 'owner' >>> t.safe_substitute(d) 'Return the unladen swallow to $owner.' 区切り文字はデフォルトは >>> import time, os.path >>> photofiles = ['img_1074.jpg', 'img_1076.jpg', 'img_1077.jpg'] >>> class BatchRename(Template): ... delimiter = '%' ... >>> fmt = input('Enter rename style (%d-date %n-seqnum %f-format): ') Enter rename style (%d-date %n-seqnum %f-format): Ashley_%n%f >>> t = BatchRename(fmt) >>> date = time.strftime('%d%b%y') >>> for i, filename in enumerate(photofiles): ... base, ext = os.path.splitext(filename) ... newname = t.substitute(d=date, n=i, f=ext) ... print('{0} --> {1}'.format(filename, newname)) img_1074.jpg --> Ashley_0.jpg img_1076.jpg --> Ashley_1.jpg img_1077.jpg --> Ashley_2.jpg テンプレートのもう一つの用途は、複数の出力形式の細かな違いからプログラムのロジックを分離することです。 これにより、XML ファイル、プレーンテキストのレポート、HTML のウェブレポートに合わせたテンプレートを差し替えて使えます。 11.3. バイナリデータレコードのレイアウトの操作¶
import struct with open('myfile.zip', 'rb') as f: data = f.read() start = 0 for i in range(3): # 最初の 3 つのファイルヘッダを表示する start += 14 fields = struct.unpack('<IIIHH', data[start:start+16]) crc32, comp_size, uncomp_size, filenamesize, extra_size = fields start += 16 filename = data[start:start+filenamesize] start += filenamesize extra = data[start:start+extra_size] print(filename, hex(crc32), comp_size, uncomp_size) start += extra_size + comp_size # 次のヘッダまで進む 11.4. マルチスレッディング¶スレッド処理 (threading) は、実行順序に依存関係のない複数のタスクを切り離す技術です。 他のタスクをバックグラウンドで実行しながらユーザー入力を受け付けるアプリケーションでは、スレッドを使って応答性を高めることができます。 関連する用途として、別のスレッドで行う計算処理と並行して I/O を実行することも挙げられます。 以下のコードでは、高水準のモジュール import threading, zipfile class AsyncZip(threading.Thread): def __init__(self, infile, outfile): super().__init__() self.infile = infile self.outfile = outfile def run(self): with zipfile.ZipFile(self.outfile, 'w', zipfile.ZIP_DEFLATED) as f: f.write(self.infile) print('Finished background zip of:', self.infile) background = AsyncZip('mydata.txt', 'myarchive.zip') background.start() print('The main program continues to run in foreground.') background.join() # バックグラウンドのタスクが終わるまで待つ print('Main program waited until background was done.') マルチスレッドアプリケーションを作る上で最も難しい問題は、データやリソースを共有するスレッド間の調整 (coordination)です。この問題を解決するため、 こうしたツールは強力ですが、小さな設計上の誤りが再現の難しい問題につながることがあります。
そのため、タスク間の調整では、あるリソースへのアクセスをすべて 1 つのスレッドに集め、 11.5. ログ記録¶
import logging logging.debug('Debugging information') logging.info('Informational message') logging.warning('Warning:config file %s not found', 'server.conf') logging.error('Error occurred') logging.critical('Critical error -- shutting down') これは以下の出力を生成します: WARNING:root:Warning:config file server.conf not found ERROR:root:Error occurred CRITICAL:root:Critical error -- shutting down デフォルトでは、 ログ記録システムは Python から直接設定することもできますし、アプリケーションを変更しなくてもカスタマイズできるよう、ユーザが編集可能な設定ファイルによって設定することもできます。 11.6. 弱参照¶Python は自動的にメモリを管理します (ほとんどのオブジェクトは参照カウント方式で管理し、 ガベージコレクション で循環参照を除去します)。オブジェクトに対する最後の参照がなくなってしばらくするとメモリは解放されます。 この方法はほとんどのアプリケーションでうまく機能しますが、オブジェクトが他から使われている間だけ、そのオブジェクトを追跡しておきたい場合もあります。
ところが、追跡するだけで参照が作られ、オブジェクトが解放されなくなってしまいます。
>>> import weakref, gc >>> class A: ... def __init__(self, value): ... self.value = value ... def __repr__(self): ... return str(self.value) ... >>> a = A(10) # 参照を作成する >>> d = weakref.WeakValueDictionary() >>> d['primary'] = a # 参照を作成しない >>> d['primary'] # オブジェクトがまだ存在すれば取得する 10 >>> del a # 唯一の参照を削除する >>> gc.collect() # 直ちにガベージコレクションを実行する 0 >>> d['primary'] # 項目は自動的に削除された Traceback (most recent call last): File "<stdin>", line 1, in <module> d['primary'] # 項目は自動的に削除された File "C:/python315/lib/weakref.py", line 46, in __getitem__ o = self.data[key]() KeyError: 'primary' 11.7. リストを操作するツール¶データ構造が必要な場面の多くは、組み込みのリスト型で対応できます。 ただし、性能上のトレードオフが異なる別の実装が必要になる場合もあります。
>>> from array import array >>> a = array('H', [4000, 10, 700, 22222]) >>> sum(a) 26932 >>> a[1:3] array('H', [10, 700])
>>> from collections import deque >>> d = deque(["task1", "task2", "task3"]) >>> d.append("task4") >>> print("Handling", d.popleft()) Handling task1 unsearched = deque([starting_node]) def breadth_first_search(unsearched): node = unsearched.popleft() for m in gen_moves(node): if is_goal(m): return m unsearched.append(m) リストの代わりの実装以外にも、標準ライブラリにはソート済みのリストを操作するための関数を備えた >>> import bisect >>> scores = [(100, 'perl'), (200, 'tcl'), (400, 'lua'), (500, 'python')] >>> bisect.insort(scores, (300, 'ruby')) >>> scores [(100, 'perl'), (200, 'tcl'), (300, 'ruby'), (400, 'lua'), (500, 'python')]
>>> from heapq import heapify, heappop, heappush >>> data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0] >>> heapify(data) # リストをヒープの順序に並べ替える >>> heappush(data, -5) # 新しい項目を追加する >>> [heappop(data) for i in range(3)] # 小さい方から 3 つの項目を取り出す [-5, 0, 1] 11.8. 10 進浮動小数点演算¶
例えば、70 セントの電話代に 5% の税金を加える計算では、10 進浮動小数点と 2 進浮動小数点で結果が異なります。 結果を最も近いセント単位に丸めると、その違いがはっきり現れます。 >>> from decimal import * >>> round(Decimal('0.70') * Decimal('1.05'), 2) Decimal('0.74') >>> round(.70 * 1.05, 2) 0.73
>>> Decimal('1.00') % Decimal('.10') Decimal('0.00') >>> 1.00 % 0.10 0.09999999999999995 >>> sum([Decimal('0.1')]*10) == Decimal('1.0') True >>> 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 == 1.0 False
>>> getcontext().prec = 36 >>> Decimal(1) / Decimal(7) Decimal('0.142857142857142857142857142857142857') |
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |