[Python-ideas] Define __fspath__() for NamedTemporaryFile and TemporaryDirectory

Ethan Furman ethan at stoneleaf.us
Fri Jun 16 16:21:42 EDT 2017


On 06/16/2017 10:36 AM, Thomas Jollans wrote:
> On 08/06/17 15:42, Antoine Pietri wrote:
>> Hello everyone!
>>
>> A very common pattern when dealing with temporary files is code like this:
>>
>>      with tempfile.TemporaryDirectory() as tmpdir:
>>          tmp_path = tmpdir.name
>>
>>          os.chmod(tmp_path)
>>          os.foobar(tmp_path)
>>          open(tmp_path).read(barquux)
>
> Is it?
>
> py> import tempfile
> py> with tempfile.TemporaryDirectory() as tmpdir:
> ...     print(tmpdir, type(tmpdir))
> ...
> /tmp/tmp2kiqzmi9 <class 'str'>
> py>

Interesting...  on 3.4 and 3.5 I get:

--> import tempfile

--> tempfile.TemporaryDirectory()
<TemporaryDirectory '/tmp/tmpy32czx2v'>

--> with tempfile.TemporaryDirectory() as tmpdir:
...   tmpdir
...
'/tmp/tmpo63icqfe'

So a <TemporaryDirectory> if used directly, and a <str> if used as a context manager.  I don't have a copy of 3.6 nor 
the future 3.7 handy, so maybe it changed there?

--
~Ethan~


More information about the Python-ideas mailing list