Skip to content

Instantly share code, notes, and snippets.

@gdevanla
Created February 27, 2015 18:21
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 gdevanla/fa21f40c0a27416c8b91 to your computer and use it in GitHub Desktop.
Save gdevanla/fa21f40c0a27416c8b91 to your computer and use it in GitHub Desktop.
import pandas as pd
import numpy as np
class InsertContext():
def __init__(self, tf):
self._tf = tf
self.__write_mode_on = False
def __enter__(self):
self._tf.df = None
self._tf.set_context(self)
self.__write_mode_on = True
return self._tf
def is_writable(self):
return self.__write_mode_on
def __exit__(self, exp, value, traceback):
self._tf._flush()
self._tf.unset_context()
self.__write_mode_on = False
class YetAnotherTableFrame():
def __init__(self, *columns):
self.df = self.__df = pd.DataFrame(data = np.zeros((0, len(columns))), columns = columns)
self._rows_to_be_inserted = []
self.__insert_context = None
def set_context(self, ic):
self.__insert_context = ic
def unset_context(self):
self.__insert_context = None
def insert(self, row):
if not self.__insert_context or not self.__insert_context.is_writable():
raise Exception("This method should be invoked from within a context")
self._rows_to_be_inserted.append(row)
def _flush(self):
other = pd.DataFrame(self._rows_to_be_inserted)
self.__df = self.__df.append(other)
self.df = self.__df
if __name__ == '__main__':
y = YetAnotherTableFrame('a', 'b', 'c')
with InsertContext(y) as tf:
tf.insert(dict(a = 1, b = 2, c = 3))
tf.insert(dict(a = 4, b = 5, c = 6))
tf.insert(dict(a = 7, b = 8, c = 9))
print(y.df)
# tricking like this, will throw an exception
ic = InsertContext(tf)
tf.set_context(ic)
tf.insert(dict(a = 7, b = 8, c = 9))
print(y.df)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment