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

标签 python python-3.x

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

问题的简短版本

为什么TemporaryDirectorywith 中使用时返回一个字符串语境?

更长版本的问题

这是一些创建临时目录 tempdir 的 Python 代码示例。并打印相应的对象:

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

>>> print(type(tempdir))
<class 'tempfile.TemporaryDirectory'>

正如预期的那样,tempdirTemporaryDirectory 的一个实例.

这是一个类似的例子,我使用了 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'>

在这种情况下,tempdir是一个字符串。当我看着 __enter__ TemporaryDirectory的方法类,我看到以下内容:

def __enter__(self):
    return self.name

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

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

最佳答案

来源tempfile.py , 在 TemporaryDirectory类(class):

def __enter__(self):
    return self.name

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

这将是不可取的:
with TemporaryDirectory('/tmp') as td:
    td.cleanup()

TemporaryDirectory除此之外没有提供任何其他方法,我认为设计决策是有道理的,尽管对开发人员来说令人惊讶的是一个缺点。如果可以避免,代码应该不足为奇。

关于Python TemporaryDirectory 在 "with"语句中使用时返回字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55348655/

相关文章:

python - 你如何获得 "My Documents"的确切路径?

Python 在换行符上拆分字符串并保留换行符

python - 如何使用 Pip (OS X) 在虚拟环境中安装 Python 包

python - 用python求解积分方程

python - Tensorflow:恢复图形和模型,然后在单个图像上运行评估

python - 无法从网站收集链接(Python)

通过 CSS 选择器进行 Python HTML 解析

python - Python 中更快的套接字

python - 将数据帧字符串列分为两列 : one with multiple text words, 和一个数字量

Python (pygame) Sin、Cos 和 Tan