[New-bugs-announce] [issue39682] pathlib.Path objects can be used as context managers

Barney Gale report at bugs.python.org
Tue Feb 18 21:10:35 EST 2020


New submission from Barney Gale <barney.gale at gmail.com>:

`pathlib.Path` objects can be used as context managers, but this functionality is undocumented and makes little sense. Example:

>>> import pathlib
>>> root = pathlib.Path("/")
>>> with root:
...     print(1)
... 
1
>>> with root:
...     print(2)
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/barney/.pyenv/versions/3.7.3/lib/python3.7/pathlib.py", line 1028, in __enter__
    self._raise_closed()
  File "/home/barney/.pyenv/versions/3.7.3/lib/python3.7/pathlib.py", line 1035, in _raise_closed
    raise ValueError("I/O operation on closed path")
ValueError: I/O operation on closed path

`Path` objects don't acquire any resources on __new__/__init__/__enter__, nor do they release any resources on __exit__. The whole notion of the path being `_closed` seems to exist purely to make impure `Path` methods unusable after exiting from the context manager. I can't personally think of a compelling use case for this, and suggest that it be removed.

----------
components: Library (Lib)
messages: 362244
nosy: barneygale
priority: normal
severity: normal
status: open
title: pathlib.Path objects can be used as context managers
versions: Python 3.8

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue39682>
_______________________________________


More information about the New-bugs-announce mailing list