Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import os.path
- INDEX_FILE = os.path.join(os.path.dirname(__file__), 'last.index')
- class LastId(int):
- """
- automatic create index file
- >>> LastId.index_file = '/tmp/last.index'
- >>> if os.path.exists(LastId.index_file):
- ... os.remove(LastId.index_file)
- >>> lastid = LastId()
- TODO: log it
- >>> open(lastid.index_file).read()
- '0'
- >>> lastid
- 0
- >>> with open(lastid.index_file, 'w') as fp:
- ... wc = fp.write('9')
- >>> lastid = LastId()
- >>> lastid
- 9
- binary method with :class:`int`
- >>> lastid == 9 , lastid != 9 , 9 == lastid , 9 != lastid
- (True, False, True, False)
- >>> lastid + 4
- 13
- >>> assert type(lastid + 4) == type(4 + lastid) == int
- >>> lastid + 1 # generate schedule ID
- 14
- >>> lastid += 4 ; lastid # increase last schedule ID
- 13
- >>> assert type(lastid) is LastId
- >>> open(lastid.index_file).read()
- '13'
- """
- index_file = INDEX_FILE
- def __new__(cls, value=None):
- """
- LastId() -> generate with value from index file;
- create index file if not exists
- LastId(9) -> generate with given value;
- not effect with index file
- :type value: int | str
- """
- if value is None:
- if os.path.exists(cls.index_file):
- value = open(cls.index_file).read().strip()
- else:
- # TODO: find the latest index number
- value = '0'
- print('TODO: log it') # TODO: log it
- with open(cls.index_file, 'w') as index_file:
- index_file.write(value)
- return super(cls, cls).__new__(cls, value)
- def __iadd__(self, b):
- """
- new an object since :class:`int` is immutable
- """
- LastId_ = LastId.__new__(LastId, self+b)
- LastId_.write()
- return LastId_
- def write(self):
- with open(self.index_file, 'w') as fp:
- fp.seek(0)
- fp.write(str(self))
- lastid = LastId()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement