LoginSignup
23
22

More than 5 years have passed since last update.

Python 3.4.0 の新機能 (1) - pathlib

Last updated at Posted at 2014-03-24

すでにあちこちで書かれている気がするけど、Python 3.4.0が 3/16 にリリースされた。3.4シリーズの一発目。

最初のPython3 (3.0.0) が出たのが2008年の12月だから、もう5年以上も経っているのか。最後の2.xシリーズである2.7の最初のリリースも2010年7月なのでそこからも4年近くが経っている。

遅いとか安定していないとかライブラリが揃っていないとか色々理由があって2.7を使い続けていた。が、「人の振り見て我が振り直せ」という格言もあり、まずは自分が書くライブラリは両対応しようかと思い立った。

そこで3を使い始めているのだが、そうこうしているうちに3.4が出ちゃった。出たからには見ておかなければということで、まずは 3.3シリーズに対する変更点。

  • PEP 428, a "pathlib" module providing object-oriented filesystem paths
  • PEP 435, a standardized "enum" module
  • PEP 436, a build enhancement that will help generate introspection information for builtins
  • PEP 442, improved semantics for object finalization
  • PEP 443, adding single-dispatch generic functions to the standard library
  • PEP 445, a new C API for implementing custom memory allocators
  • PEP 446, changing file descriptors to not be inherited by default in subprocesses
  • PEP 450, a new "statistics" module
  • PEP 451, standardizing module metadata for Python's module import system
  • PEP 453, a bundled installer for the pip package manager
  • PEP 454, a new "tracemalloc" module for tracing Python memory allocations
  • PEP 456, a new hash algorithm for Python strings and binary data
  • PEP 3154, a new and improved protocol for pickled objects
  • PEP 3156, a new "asyncio" module, a new framework for asynchronous I/O

https://www.python.org/download/releases/3.4.0/ にはリンク付きでリストされているのでそちらを見た方が早いが、ドキュメントを読んだだけでは今ひとつピンと来ない。

ならば使ってみるのが一番だが、一度に全てはできない(そして読む方も疲れる)ので一つずつ使ってみることにする。

上から順で、今回は pathlib について。Pathlibは「ファイルシステムのパスを扱うオブジェクト指向なモジュール」というモノらしい。使ったことがなかったが pypiにもあがっていて、Python2,7, 3,2, 3.3でも pip installすれば使えるらしい。

ドキュメントの拾い読みで幾つか試してみる。まずはカレントディレクトリの下にあるディレクトリのリストを取得するコード。

# Pathクラスをインポート
from pathlib import Path 

# 現ディレクトリを表すPathオブジェクトを生成
p = Path('.')

# for文でまわしてプリントアウト
for p in p.iterdir():
    if x.is_dir():
        print (x)

# 後で使うためにlistで取得
dirlist = [x for x in p.iterdir() if x.is_dir()]
...

面白いのは除算演算子を使って階層アクセスできること。
例えば、次のようにできる。

# Pathクラスをインポート
from pathlib import Path 

# 絶対パスを指定してPathオブジェクト生成
usr_local_path = Path('/usr/local')

# さらに下の階層のファイルを表すPathオブジェクト
python_path = usr_local_path  / 'bin' / 'python'

# Symbolic linkの場合は元ファイルのパスも得られる
python_real_path = python_path.resolve()

この他、Pathオブジェクトのメソッドとしてopen()はstat()などがあり、ファイル操作で出来ることはひと通り出来るようだ。

os.pathとの住み分けが気になるところだが、徐々にpathlibを使うようになっていくのかな。ちょっと時間切れなので試すのはまた今度。念のため、標準ドキュメント中のpathlibの説明はここ

そして残りの「3.4新規追加機能」も試していきたいのだが、このペースで書いていると終わる頃には次のリリースがでてしまっているかも(?)

23
22
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
23
22