Advertisement
Guest User

Untitled

a guest
Jul 26th, 2017
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.00 KB | None | 0 0
  1. import os.path
  2.  
  3.  
  4. INDEX_FILE = os.path.join(os.path.dirname(__file__), 'last.index')
  5.  
  6.  
  7. class LastId(int):
  8. """
  9. automatic create index file
  10. >>> LastId.index_file = '/tmp/last.index'
  11. >>> if os.path.exists(LastId.index_file):
  12. ... os.remove(LastId.index_file)
  13. >>> lastid = LastId()
  14. TODO: log it
  15. >>> open(lastid.index_file).read()
  16. '0'
  17. >>> lastid
  18. 0
  19. >>> with open(lastid.index_file, 'w') as fp:
  20. ... wc = fp.write('9')
  21. >>> lastid = LastId()
  22. >>> lastid
  23. 9
  24.  
  25. binary method with :class:`int`
  26. >>> lastid == 9 , lastid != 9 , 9 == lastid , 9 != lastid
  27. (True, False, True, False)
  28. >>> lastid + 4
  29. 13
  30. >>> assert type(lastid + 4) == type(4 + lastid) == int
  31. >>> lastid + 1 # generate schedule ID
  32. 14
  33. >>> lastid += 4 ; lastid # increase last schedule ID
  34. 13
  35. >>> assert type(lastid) is LastId
  36. >>> open(lastid.index_file).read()
  37. '13'
  38. """
  39. index_file = INDEX_FILE
  40.  
  41. def __new__(cls, value=None):
  42. """
  43. LastId() -> generate with value from index file;
  44. create index file if not exists
  45. LastId(9) -> generate with given value;
  46. not effect with index file
  47.  
  48. :type value: int | str
  49. """
  50. if value is None:
  51. if os.path.exists(cls.index_file):
  52. value = open(cls.index_file).read().strip()
  53. else:
  54. # TODO: find the latest index number
  55. value = '0'
  56. print('TODO: log it') # TODO: log it
  57. with open(cls.index_file, 'w') as index_file:
  58. index_file.write(value)
  59. return super(cls, cls).__new__(cls, value)
  60.  
  61. def __iadd__(self, b):
  62. """
  63. new an object since :class:`int` is immutable
  64. """
  65. LastId_ = LastId.__new__(LastId, self+b)
  66. LastId_.write()
  67. return LastId_
  68.  
  69. def write(self):
  70. with open(self.index_file, 'w') as fp:
  71. fp.seek(0)
  72. fp.write(str(self))
  73.  
  74. lastid = LastId()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement