Skip to content
Prev Previous commit
Next Next commit
Add back reference to origin df to protect against broken chains of v…
…iews
  • Loading branch information
Nick Eubank committed Jan 13, 2016
commit 9085bea774f358eb4e3fe72b90610820eff42b6c
9 changes: 7 additions & 2 deletions pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ class NDFrame(PandasObject):
'is_copy', '_subtyp', '_index',
'_default_kind', '_default_fill_value', '_metadata',
'__array_struct__', '__array_interface__', '_children',
'_is_column_view']
'_is_column_view', '_original_parent']
_internal_names_set = set(_internal_names)
_accessors = frozenset([])
_metadata = []
Expand All @@ -108,6 +108,7 @@ def __init__(self, data, axes=None, copy=False, dtype=None,
object.__setattr__(self, '_item_cache', {})
object.__setattr__(self, '_children', weakref.WeakValueDictionary())
object.__setattr__(self, '_is_column_view', False)
object.__setattr__(self, '_original_parent', weakref.WeakValueDictionary())


def _validate_dtype(self, dtype):
Expand Down Expand Up @@ -1244,7 +1245,11 @@ def _execute_copy_on_write(self):
def _add_to_children(self, view_to_append):
self._children[id(view_to_append)] = view_to_append


if len(self._original_parent) is 0:
view_to_append._original_parent['parent'] = self
else:
self._original_parent['parent']._add_to_children(view_to_append)

def __delitem__(self, key):
"""
Delete item
Expand Down
17 changes: 17 additions & 0 deletions pandas/tests/test_generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -1808,6 +1808,23 @@ def test_copy_on_write(self):
self.assertTrue(v.loc[0] == -88)
self.assertTrue(v._is_view)

###
# Make sure that no problems if view created on view and middle-view
# gets deleted
#
df = pd.DataFrame({'col1':[1,2], 'col2':[3,4]})
v1 = df.loc[0:0,]
self.assertTrue(len(df._children)==1)

v2 = v1.loc[0:0,]
v2_copy = v2.copy()
self.assertTrue(len(df._children)==2)

del v1

df.loc[0:0, 'col1'] = -88

tm.assert_frame_equal(v2, v2_copy)



Expand Down