0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

TemporaryDirectoryとwith文の仕組み

Posted at

わかる

f.py
path = __file__
f = open(path)
print(type(f))       # <class '_io.TextIOWrapper'>
f.close()
with open(__file__) as fw:
    print(type(fw))  # <class '_io.TextIOWrapper'>

with文はスコープを抜けるとデストラクタが呼ばれるため上記の場合f.close()を省略できるというスグレモノである。よくある例なので特にどうということはない。

わからない

d.py
import tempfile
t = tempfile.TemporaryDirectory()
print(type(t))       # <class 'tempfile.TemporaryDirectory'>
with tempfile.TemporaryDirectory() as tt:
    print(type(tt))  # <class 'str'> ←なんで文字列?
    print(tt)        # /tmp/tmp6nng15e8 ←中身はディレクトリパス

with文を使うとasで渡した変数に文字列、この場合は一時ディレクトリのパスが入りました。

どうしてこうなった?

ドキュメントを読むのが正規ルート。
3. データモデル — Python 3.7.3 ドキュメント

object.__enter__(self)
コンテキストマネージャのの入り口で実行される処理です。 with 文は、文の as 節で規定された値を返すこのメソッドを呼び出します。

tempfile.py
class TemporaryDirectory(object):
...
    def __enter__(self):
        return self.name

nameを返すようになっています。with文によってcleanup()メソッド呼ばれるし、他に必要なメソッドがない、必要になるとしたらパスだけだから__enter__で名前だけ返してやればいいよねって言うことか。

0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?