Skip to content

Instantly share code, notes, and snippets.

@fcasco
Created June 15, 2013 15:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fcasco/5788558 to your computer and use it in GitHub Desktop.
Save fcasco/5788558 to your computer and use it in GitHub Desktop.
Context manager to avoid running a task twice
#!/usr/bin/env python
import unittest
class Avoid_twice():
tasks_filename = '/tmp/avoid_twice'
def __init__(self, task_name):
self.current_task = task_name
def __enter__(self):
with open(self.tasks_filename) as i:
return self.current_task in i.read()
def __exit__(self, exc_type, exc_value, traceback):
if exc_type is None:
with open(self.tasks_filename, 'a') as o:
o.write(self.current_task + '\n')
class AvoidTwiceTestCases(unittest.TestCase):
def test_once(self):
l = []
with Avoid_twice('task_name') as done:
if not done:
l.append(42)
with Avoid_twice('task_name') as done:
if not done:
l.append(42)
self.assertEqual(l, [42])
if __name__ == '__main__':
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment