7
\$\begingroup\$

I decided to write a tiny class to automatically write and delete a file given filename and content. It is intended to make testing IO less verbose. I include a small example usage.

temporary.py

import os
class Temporary:
 def __init__(self, name, content):
 self.name = name
 self.content = content
 def __enter__(self):
 with open(self.name, 'w+') as f:
 f.write(self.content)
 def __exit__(self,_,__,___):
 os.remove(self.name)

first_word.py

import doctest
from temporary import Temporary
def first_word_of_each_line(filename):
 """
 >>> txt = '\\n'.join(['first line', 'second line', 'bar bar'])
 >>> with Temporary('foo.txt', txt): first_word_of_each_line('foo.txt')
 ['first', 'second', 'bar']
 """
 with open(filename) as f:
 lines = f.read().splitlines()
 return [line.split()[0] for line in lines]
if __name__ == "__main__":
 doctest.testmod()
asked May 19, 2015 at 13:15
\$\endgroup\$
3
  • \$\begingroup\$ Better to patch open using something like pypi.python.org/pypi/mock \$\endgroup\$ Commented May 19, 2015 at 17:28
  • \$\begingroup\$ What was wrong with the various temporary file classes in the tempfile module? \$\endgroup\$ Commented May 21, 2015 at 14:07
  • \$\begingroup\$ @GarethRees nothing this is just an exercise with with not intended to be used for serious purposes \$\endgroup\$ Commented May 28, 2015 at 18:06

1 Answer 1

3
\$\begingroup\$

There, well, really isn't much to review here, so I have just a couple of points on this.

  • Add a docstring to the class Temporary. Describe what this class does in detail, and flesh it out with useful information about arguments as well.
  • You're missing some whitespace in between parameters in your __exit__ declaration. It should look like this def __exit__(self, _, __, ___).
  • You should add a method like write_to_file so that the user can change the contents of the file during runtime, before it's deleted.
  • As mentioned by @GarethRees, there's already a Python module built for this kind of use, tempfile.

I hope this helps! If there's anything else that you want me to cover on this, mention it in the comments, and I'll see if I can cover it.

answered Jun 7, 2015 at 1:01
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.