Skip to content

Commit a19fd9b

Browse files
committed
Support deepcopy of DBRef PYTHON-169
1 parent f70a1b7 commit a19fd9b

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

bson/dbref.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
"""Tools for manipulating DBRefs (references to MongoDB documents)."""
1616

1717
from bson.son import SON
18+
from copy import deepcopy
1819

1920

2021
class DBRef(object):
@@ -115,3 +116,13 @@ def __hash__(self):
115116
"""
116117
return hash((self.__collection, self.__id,
117118
self.__database, self.__kwargs))
119+
120+
def __deepcopy__(self, memo):
121+
"""Support function for `copy.deepcopy()`.
122+
123+
.. versionadded:: 1.10
124+
"""
125+
return DBRef(deepcopy(self.__collection, memo),
126+
deepcopy(self.__id, memo),
127+
deepcopy(self.__database, memo),
128+
deepcopy(self.__kwargs, memo))

test/test_dbref.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@
2121
from bson.objectid import ObjectId
2222
from bson.dbref import DBRef
2323

24+
from copy import deepcopy
25+
2426

2527
class TestDBRef(unittest.TestCase):
2628

@@ -90,6 +92,21 @@ def test_kwargs(self):
9092
self.assertEqual("bar", DBRef("coll", 5, foo="bar").foo)
9193
self.assertRaises(KeyError, getattr, DBRef("coll", 5, foo="bar"), "bar")
9294

95+
def test_deepcopy(self):
96+
a = DBRef('coll', 'asdf', 'db', x=[1])
97+
b = deepcopy(a)
98+
99+
self.assertEqual(a, b)
100+
self.assertNotEqual(id(a), id(b.x))
101+
self.assertEqual(a.x, b.x)
102+
self.assertNotEqual(id(a.x), id(b.x))
103+
104+
b.x[0] = 2
105+
self.assertEqual(a.x, [1])
106+
self.assertEqual(b.x, [2])
107+
108+
109+
93110

94111
if __name__ == "__main__":
95112
unittest.main()

0 commit comments

Comments
 (0)