#!/usr/bin/env python
from __future__ import with_statement
from time import sleep
from pickle import dump, load
import os

class checkpointed_range(list):
	def __init__ (self, limit):
		self.current = 0
		self.limit = limit
		self.chkpt_file = "./checkpoint.dat";
		self.chkpt_restore()

	def __iter__ (self):
		return self

	def next (self):
		if self.current >= self.limit:
			self.chkpt_clean()
			raise StopIteration
		
		sleep(1);
		self.current += 1
		self.chkpt()
		return self.current - 1
	
	def chkpt (self):
		with file(self.chkpt_file, "w") as f:
			dump((self.current, self.limit), f)

	def chkpt_restore (self):
		if os.path.exists(self.chkpt_file):
			with file(self.chkpt_file, "r") as f:
				(self.current, self.limit) = load(f)
			self.chkpt_clean()

	def chkpt_clean (self):
		os.unlink(self.chkpt_file)

if __name__ == "__main__":
	for i in checkpointed_range(10):
		print i


