今まで全然追いかけてなかったのですが、僕が過去に書いたPythonモジュールを、Python3に対応させろやというコメントが複数件来まして、それでも放置してたらpull requestまで送りつけられたので、重い腰を上げて調べました。
3.0〜3.3までのWhat’s Newのページを眺めてみて、目に留まった項目をチョロチョロ書いてみます。というか3.0ってもう4年以上前にリリースされてるんですね。全然普及してる感じがしないですけど。
2008.12.03 | What’s New in Python 3.0 |
2009.06.27 | What’s New in Python 3.1 |
2011.02.20 | What’s New in Python 3.2 |
2012.09.29 | What’s New in Python 3.3 |
とりあえず最新Stableの3.3をインストールしないと試せないですね。brewだとformulaがまだ無くて、この辺からも普及してなさが伺えますが、仕方が無くMac用のインストーラを使いました。
またPython3.3からはvenvというvirtualenvと似た機能がビルトインされている様なので、そちらを使って環境を作ります。本体はvenvというモジュールですが、コマンドライン用にpyvenvというコマンドが用意されています。venvはデフォルトでdistributeもpipも入らないので、自前で入れる必要があって若干面倒です。まぁ公式モジュールなので仕方ないかもしれません。あとiPythonが3に対応してたので安心しました。
$ which pyvenv-3.3 /usr/local/bin/pyvenv-3.3 $ pyvenv-3.3 py3x_test $ tree . ├── bin │ ├── activate │ ├── pydoc │ ├── python -> python3.3 │ ├── python3 -> python3.3 │ └── python3.3 -> /Library/Frameworks/Python.framework/Versions/3.3/bin/python3.3 ├── include ├── lib │ └── python3.3 │ └── site-packages └── pyvenv.cfg $ curl -O http://python-distribute.org/distribute_setup.py $ python distribute_setup.py $ easy_install pip $ pip install ipython $ ipython3 Python 3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 01:25:11) Type "copyright", "credits" or "license" for more information. IPython 0.13.1 -- An enhanced Interactive Python. ? -> Introduction and overview of IPython's features. %quickref -> Quick reference. help -> Python's own help system. object? -> Details about 'object', use 'object??' for extra details.
環境も出来たので、まずは新しい構文を見てみます。
# printはもう式じゃない >> print 'Hello Python 3 World!' File "<ipython-input-1-7399c5fe436c>", line 1 print 'Hello Python 3 World!' ^ SyntaxError: invalid syntax >> print('Hello Python 3 World!') Hello Python 3 World! # 文字列リテラルはデフォルトでユニコード >> 'あいうえお' 'あいうえお' >> 'あいうえお'.encode('utf-8') b'\xe3\x81\x82\xe3\x81\x84\xe3\x81\x86\xe3\x81\x88\xe3\x81\x8a' # ユニコードリテラルを表すuは意味なくなってる >> 'あいうえお'.__class__ builtins.str >> u'あいうえお'.__class__ builtins.str # nonlocalが使えるようになった >> def outer(): x = 10 def inner(): nonlocal x x *= 2 inner() print(x) >> outer() 20 # unpackで*で可変長受けれるようになってる >> a, *b, c = [1,2,3,4,5] >> print b [2, 3, 4] # タプルを受けてもリストになる >> x, *y, z = (1,2,3,4,5) >> y [2,3,4] >> y.__class__ builtins.list # set用のリテラルが追加 >> {1,2}.__class__ >> builtins.set # withブロックで複数変数を同時にバインド可能に >> with open('data.in', 'r') as infile, open('data.out', 'w') as outfile: >> outfile.write(infile.read()) # yield from 式が追加でジェネレータを入れ子に出来る >> def g(x): yield from range(x) >> for val in g(3): print(val) 0 1 2 # exceptの書き方が変わった >> try: pass except IOError as e: print(e)
とりあえず目についたのはこんなところです。printが式じゃなくなったのは残念としか言いようが無いですが、他は地味に良くなっていますね。特にnonlocalでPythonのクロージャが残念というのが結構解消されたのは大きいです。unpackは直感に近い挙動になって嬉しいですし、yield fromは個人的に色々使ってみたい機能です。でもuリテラルって一体。。。
次に標準ライブラリを見てみます。What’s Newには沢山の修正点が書かれているのですが、urllibがまとまった事くらいしかピンとこなくて、まぁまぁPython使えてる気になってましたけど、細かい機能は把握出来てないなぁと思いました。
# urllib, urllib2, urlparseがurllibモジュールにまとめられた >> from urllib import request >> request.open(request.Request('http://yahoo.co.jp')) <http.client.HTTPResponse at 0x101c01810> >> from urllib import parse >> parse.urlparse('http://baseball.yahoo.co.jp/npb/') ParseResult(scheme='http', netloc='baseball.yahoo.co.jp', path='/npb/', params='', query='', fragment='') # 上述のvenvモジュールが追加 >> import venv >> venv? Type: module String Form:<module 'venv' from '/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/venv/__init__.py'> File: /Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/venv/__init__.py Docstring: Virtual environment (venv) package for Python. Based on PEP 405. Copyright (C) 2011-2012 Vinay Sajip. Licensed to the PSF under a contributor agreement. usage: python -m venv [-h] [--system-site-packages] [--symlinks] [--clear] [--upgrade] ENV_DIR [ENV_DIR ...] Creates virtual Python environments in one or more target directories. positional arguments: ENV_DIR A directory to create the environment in. optional arguments: -h, --help show this help message and exit --system-site-packages Give the virtual environment access to the system site-packages dir. --symlinks Attempt to symlink rather than copy. --clear Delete the environment directory if it already exists. If not specified and the directory exists, an error is raised. --upgrade Upgrade the environment directory to use this version of Python, assuming Python has been upgraded in-place.
大した事書けなかったですが、何となくPython3が把握できました。ボチボチPython3使い初めても良いかなぁ言う状況になってきていると思います。
ただ個人的にはDjangoがまだ3をサポートしてない(Django1.5で実験的にサポートするらしい)ので、まだ本気は出さなくても良いけど、ちょっとずつ使い始めようかなとそういう今日この頃です。