Python 3.4
Python 3.4
ふるかわとおる

@torufurukawa

39
プログラマ
Python 3.4
• 2013年8月3日: alpha 1
• 2013年9月9日: alpha 2
• 2013年9月29日: alpha 3
• 2013年10月20日: alpha 4
• 2013年11月23日: @torufurukawa 誕生日
• 2013年11月24日: beta 1
---- 新機能追加はここまで ----
Python 3.4
•
•
•
•

2014年1月5日: beta 2
2014年1月19日: candidate 1
2014年2月2日: candidate 2
2014年2月23日: final
What's New in Python 3.4
構文/文法の変更なし
What's New in Python 3.4
What's New in Python 3.4
追加ライブラリ
• asyncio ... 非同期I/O
• enum ... 列挙型
• ensurepip ... pip インストーラの管理
• pathlib ... オブジェクト指向パス
• selectors ... 高レベルI/O マルチプレクス
• statistics ... 統計関数
• tracemalloc ... メモリ確保のトレーサ
What's New in Python 3.4
実装
• file descriptor
• Isolated mode
• Codecs for non-text encodings
What's New in Python 3.4
ライブラリの向上
• Single-dispatch generic functions in functoools
• New pickle protocol 4
• SHA-3 (Keccak) support for hashlib.
• TLSv1.1 and TLSv1.2 support for ssl.
• multiprocessing now has option to avoid using
os.fork() on Unix
What's New in Python 3.4
CPython implementation
• Safe object finalization
• Configurable memory allocators
• Secure and interchangeable hash algorithm
• Improve finalization of Python modules to avoid setting
their globals to None, in most cases (issue 18214).
• A more efficient marshal format (issue 16475).
• “Argument Clinic”, an initial step towards providing
improved introspection support for builtin and standard
library extension types implemented in C (PEP 436)
ライブラリ見ましょう
• もう新機能の追加はないし
• 内部実装のこととか難しいし
asyncio
• 「asyncore: included batteries do not fit」
• シングルスレッドで並行処理するライブラリ
– コルーチン
– I/Oマルチプレクス
– イベントループ
– etc.
asyncio
ドキュメントを見ると...
免責事項:
ドキュメントは、まだ。
Beta が終了する頃にはできてるといいな。
それまでは PEP 読んで。
asyncio
asyncio
•
•
•
•
•
•

長い
「tulip」がベースらしい
ぐぐる
リンクたらい回し
PyPI
PEP へリンク
asyncio
enum
モード、選択肢、戻り値の候補が固定されてい
て、かつ、比較が必要。
▼
定数を安全に記述できる。
〜3.3

enum
>>> RED = 1
>>> GREEN = 2
>>> SPAM = 1
>>> HAM = 2
>>> RED == SPAM
True
〜3.3

enum
>>> RED * HAM == HAM
True
>>> RED
1 # 分かりにくい
〜3.3

enum
>>> RED = "color:red"
>>> GREEN = "color:green"

# だるい
3.4

enum
from enum import Enum
class Color(Enum):
red = 1
green = 2
3.4

enum
>>> Color.red == Food.spam
False
>>> Color.red * 2
TypeError: unsupported operand type(s)
for *: 'Color' and 'int'

>>> Color.red
Color.red
3.4

enum
>>> class Color(Enum):
...
red = "#FF0000"
...
green = "#00FF00"
>>> Color.red.name
"red"
>>> Color.red.value
"#FF0000"
ensurepip
サードパーティのライブラリを使う。
▼
パッケージインストーラが事実上はいってくる。
〜3.3

ensurepip
$ wget
https://bitbucket.org/pypa/setuptools/src/1.4.1
/ez_setup.py
$ wget
https://raw.github.com/pypa/pip/develop/contr
ib/get-pip.py
$ ez_setup.py
$ get-pip.py
$ pip install virtualenv
http://pelican.aodag.jp/python34noensurepipsoretopyvenvnogeng-xin.html
ensurepip
• pip がインストールされた状態にする
ためのライブラリ
• make install したら呼び出されてる
• 本家の OS X 用インストーラでも呼ばれている
ensurepip
3.4

ensurepip
$ pip ipython
$ pyvenv-3.4 venv
$ venv/bin/pip install kaaedit
pathlib
パス、ディレクトリ、ファイルを操作する。
▼
パスをオブジェクトっぽく操作できる。
〜3.3

pathlib
import os.path
parent_dir = (
os.path.abspath(
os.path.dirname(
os.path.dirname(__file__)
)
)
)
〜3.3

pathlib
from os.path import dirname,
abspath
parent_dir = (
abspath(dirname(dirname(__file__))
)
〜3.3

pathlib
from os.path import (dirname,
abspath, join)
target_dir = abspath(
join(
dirname(dirname(__file__)),
'target'
)
)
〜3.3

pathlib
from glob import glob
for p in glob(os.path.join(t, '*.py')):
# do something
...
fin = open(p)
3.4

pathlib
from pathlib import Path
p = Path(__file__).parent.resolve()
t = p.joinpath('target')
t = p / 'target'
3.4

pathlib
for p in target_dir.glob('*.py'):
pass
fin = p.open()
selectors
I/Oをイベント駆動で書きたいんだけど、
select/poll/epoll の薄いラッパだとだるい
▼
I/O マルチプレクスを手軽に。
selectors
• select モジュールが低レベルすぎる
• 環境ごとに自力で選ぶ
– /dev/poll ... Solaris
– epoll ... Linux
– poll ... どこでも
– kqueue ... BSD
– select ... どこでも

• イベントの種類も個別に違うし
3.4

selectors
s = selectors.DefaultSelector()
s.register(mysocket, selectors.EVENT_READ)
for key, events in s.select():
if events & selectors.EVENT_READ:
print(key.fileobj.recv(1024))
statistics
ちょっとした統計が必要
▼
平均、標準偏差なんかを正確に計算する。
〜3.3

statistics
>>> def var(data):
...
n = len(data)
...
ss = sum(x**2 for x in data) –
...
(sum(data)**2)/n
... return ss/(n-1)
>>> var([1,2,3,4]))
1.6666666666666667
>>> var([x+1e12 for x in [1,2,3,4]]*100))
-1377834120.02005
〜3.3

statistics
import numpy
a = numpy.array(data, float)
a.var()
3.4

statistics
import statistics
statistics.variance([1,2,3,4]))
statistics.variance([x+1e12 for x
in [1,2,3,4]]*100))
tracemalloc
import tracemalloc
tracemalloc.start()
x = [str(v) for v in range(1000)]
snapshot = tracemalloc.take_snapshot()
for stat in snapshot.statistics('lineno'):
print(stat)
tracemalloc
foo.py:7: size=59.4 KiB, count=1001, average=61 B
foo.py:6: size=28 B, count=1, average=28 B
おしまい

Introduction to Python 3.4 as of beta 1