Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

why does TemporaryDirectory change type within a "with" block?

In python3 console

>>> x1=tempfile.TemporaryDirectory()
>>> print(type(x1))
<class 'tempfile.TemporaryDirectory'>
>>> with tempfile.TemporaryDirectory() as x2:
...   print(type(x2))
... 
<class 'str'>

Why is x1 a TemporaryDirectory and x2 a str?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Because with foo() as x has x take on the value of foo().__enter__()‘s return value.

x = foo() is a different thing.

See here for the implementation of TemporaryDirectory; it does a bunch of things, but the important thing is that entering the context manager returns the directory name, and exiting the context manager destroys that named directory.

class TemporaryDirectory:
   ...

    def __enter__(self):
        return self.name

   ...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading