Advertisement
Guest User

Untitled

a guest
Apr 18th, 2015
209
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.66 KB | None | 0 0
  1. import pandas as pd
  2. import numpy as np
  3.  
  4.  
  5. class InsertContext():
  6. def __init__(self, tf):
  7. self._tf = tf
  8. self.__write_mode_on = False
  9.  
  10. def __enter__(self):
  11. self._tf.df = None
  12. self._tf.set_context(self)
  13. self.__write_mode_on = True
  14. return self._tf
  15.  
  16. def is_writable(self):
  17. return self.__write_mode_on
  18.  
  19. def __exit__(self, exp, value, traceback):
  20. self._tf._flush()
  21. self._tf.unset_context()
  22. self.__write_mode_on = False
  23.  
  24.  
  25.  
  26. class YetAnotherTableFrame():
  27.  
  28. def __init__(self, *columns):
  29.  
  30. self.df = self.__df = pd.DataFrame(data = np.zeros((0, len(columns))), columns = columns)
  31.  
  32. self._rows_to_be_inserted = []
  33. self.__insert_context = None
  34.  
  35.  
  36. def set_context(self, ic):
  37. self.__insert_context = ic
  38.  
  39. def unset_context(self):
  40. self.__insert_context = None
  41.  
  42. def insert(self, row):
  43.  
  44. if not self.__insert_context or not self.__insert_context.is_writable():
  45. raise Exception("This method should be invoked from within a context")
  46.  
  47. self._rows_to_be_inserted.append(row)
  48.  
  49.  
  50. def _flush(self):
  51.  
  52. other = pd.DataFrame(self._rows_to_be_inserted)
  53. self.__df = self.__df.append(other)
  54. self.df = self.__df
  55.  
  56.  
  57. if __name__ == '__main__':
  58.  
  59.  
  60. y = YetAnotherTableFrame('a', 'b', 'c')
  61.  
  62. with InsertContext(y) as tf:
  63. tf.insert(dict(a = 1, b = 2, c = 3))
  64. tf.insert(dict(a = 4, b = 5, c = 6))
  65. tf.insert(dict(a = 7, b = 8, c = 9))
  66.  
  67. print(y.df)
  68.  
  69. # tricking like this, will throw an exception
  70. ic = InsertContext(tf)
  71. tf.set_context(ic)
  72. tf.insert(dict(a = 7, b = 8, c = 9))
  73.  
  74. print(y.df)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement