OrderDict
Python2のstrはPython3のbytes
import sys print sys.version if sys.version_info <= (3, 0, 0): print 'hoge'
callableは3.0 3.1で消滅し、3.2で復活した
execfile
with
from __future__ import with_statement with open('test_py.py', 'r') as f: print f.read()
Python3ではprintを文ではなく式として解釈する
print 'spam', 'egg', 'ham' # Python2 spam egg ham print ('spam', 'egg', 'ham') # Python2 ('spam', 'egg', 'ham') print ('spam', 'egg', 'ham') # Python3 spam egg ham print ('done') # done
よりPythonicなPythonを目指して(前編):Python 3が後方互換性を捨ててでも求めたもの (1/2) - @IT
「評価式」「関数やメソッドの呼び出し」「オブジェクトのリテラル表記」などが「式」として分類されます。式は1行に複数置くことができます。
「if文」「for文」「try〜except文」「import文」「代入文」などが文として分類されます。基本的に、1行には複数の文を書くことができません。いい換えると、文は改行を伴います。
なんかPython2とPython3で色々対応するのは面倒ではないか?
How to keep compatibility with both python2 and 3
2to3 lib2to3ライブラリを利用してPython2のコードをPython3に変換する
Pros
- Python2の資産をすぐにPython3に対応
- setuptoolsはsetupでインストール時変換
Cons
- 遅い
- テスト実行のために毎回2to3が必要
- 変換後のコードでエラーが発生したらどこでエラってるか分からず面倒
(3to2もあるけど、これはすごい面倒)
両対応コードを書く
Pros
2to3の問題が発生しない(デバッグしやすい)
Cons
Python2.4対応は絶望的
2.5を投げすてたい
差異の吸収を自分でやる必要がある
25.4. 2to3 - Automated Python 2 to 3 code translation — Python v2.7.5 documentation
def greet(name): print "Hello, {0}!".format(name) print "What's your name?" name = raw_input() greet(name)
2to3で変換
$ 2to3 -w example.py
def greet(name): print("Hello, {0}!".format(name)) print("What's your name?") name = input() greet(name)
Python 2.xと3.xの間にコンパチなレイヤーを提供する「Six」 | TRIVIAL TECHNOLOGIES 4 @ats のイクメン日記
パッケージングツール
setuptoolsを使うべきか否か
2011
distutils
easy_install的なのもない
setuptoolsがeasy_installを提供
pipはeasy_installより便利なコマンドを提供
2012
setuptoolsはもう更新されてないからdistributeを使おう
packagingは3.3リリース直前に消滅
2013
distlib packagingで不足していた下位レイヤ 3.4で同梱予定
setup.pyは2,3互換コードで書く
2to3もsixも諸般の事情により使えない
特定バージョンの場合だけ、依存パッケージをインストールする
特定バージョンの場合だけ、依存パッケージを指定する
アナウンスもなしに特定バージョンのサポートをやめることもある
対応しているバージョンは書こう