Python TemporaryDirectory 在“with”语句中使用时返回字符串

iga*_*gal 8 python python-3.x

Python TemporaryDirectory 在“with”语句中使用时返回字符串

问题的简短版本

为什么在上下文TemporaryDirectory中使用时返回字符串with

问题的较长版本

下面是一些 Python 代码的示例,它创建一个临时目录tempdir并打印相应的对象:

>>> import tempfile
>>> tempdir = tempfile.TemporaryDirectory(dir="/tmp")
>>> print(tempdir)
<TemporaryDirectory '/tmp/tmpf2yh8xu9'>

>>> print(type(tempdir))
<class 'tempfile.TemporaryDirectory'>
Run Code Online (Sandbox Code Playgroud)

正如预期的那样,tempdir是 的一个实例TemporaryDirectory

这是一个类似的例子,我with在调用时使用了一个语句TemporaryDirectory

>>> import tempfile
>>> with tempfile.TemporaryDirectory(dir="/tmp") as tempdir: print(tempdir)
/tmp/tmp7mlmzegs

>>> with tempfile.TemporaryDirectory(dir="/tmp") as tempdir: print(type(tempdir))
<class 'str'>
Run Code Online (Sandbox Code Playgroud)

在本例中,tempdir是一个字符串。当我查看__enter__该类的方法时TemporaryDirectory,我看到以下内容:

def __enter__(self):
    return self.name
Run Code Online (Sandbox Code Playgroud)

果然 - 看起来返回的是一个字符串而不是对象本身。

造成这种差异的原因是什么?为什么该__enter__方法返回文件名而不是文件对象?

Gri*_*mar 5

来自 的来源tempfile.py,在TemporaryDirectory类中:

def __enter__(self):
    return self.name
Run Code Online (Sandbox Code Playgroud)

至于“为什么”:__enter____exit__方法在一个块中控制类的行为with,显然,TemporaryDirectory类选择只给你位置 - 可能是为了避免篡改类和之后的清理。例如,在块.cleanup()结束之前调用with

这将是不可取的:

with TemporaryDirectory('/tmp') as td:
    td.cleanup()
Run Code Online (Sandbox Code Playgroud)

由于TemporaryDirectory除此之外没有提供其他方法,我认为设计决策是有意义的,尽管对开发人员来说惊喜是一个缺点。如果可以避免的话,代码就不足为奇了。