Skip to content

Scrapy, a fast high-level web crawling & scraping framework for Python.

added copy method to item

Nicolás Ramírez6df274bba535
diff --git a/docs/topics/items.rst b/docs/topics/items.rst
index 1406fa61b..124d6996a 100644
--- a/docs/topics/items.rst
+++ b/docs/topics/items.rst
@@ -157,6 +157,10 @@ Copying items::
>>> print product2
Product(name='Desktop PC', price=1000)
+ >>> product3 = product2.copy()
+ >>> print product3
+ Product(name='Desktop PC', price=1000)
+
Creating dicts from items::
>>> dict(product) # create a dict from all populated values
diff --git a/scrapy/item.py b/scrapy/item.py
index 1d3aae5ac..265fcb8a5 100644
--- a/scrapy/item.py
+++ b/scrapy/item.py
@@ -4,6 +4,7 @@ Scrapy Item
See documentation in docs/topics/item.rst
"""
+from copy import deepcopy
from pprint import pformat
from UserDict import DictMixin
@@ -76,6 +77,9 @@ class DictItem(DictMixin, BaseItem):
def __repr__(self):
return pformat(dict(self))
+ def copy(self):
+ return self.__class__(self)
+
class Item(DictItem):
diff --git a/scrapy/tests/test_item.py b/scrapy/tests/test_item.py
index 79cac5fc8..764c94d6e 100644
--- a/scrapy/tests/test_item.py
+++ b/scrapy/tests/test_item.py
@@ -98,8 +98,8 @@ class ItemTest(unittest.TestCase):
def test_metaclass(self):
class TestItem(Item):
name = Field()
- keys = Field()
- values = Field()
+ keys = Field()
+ values = Field()
i = TestItem()
i['name'] = u'John'
@@ -114,8 +114,8 @@ class ItemTest(unittest.TestCase):
def test_metaclass_inheritance(self):
class BaseItem(Item):
name = Field()
- keys = Field()
- values = Field()
+ keys = Field()
+ values = Field()
class TestItem(BaseItem):
keys = Field()
@@ -133,6 +133,15 @@ class ItemTest(unittest.TestCase):
i['name'] = u'John'
self.assertEqual(dict(i), {'name': u'John'})
+ def test_copy(self):
+ class TestItem(Item):
+ name = Field()
+ item = TestItem({'name':'lower'})
+ copied_item = item.copy()
+ self.assertNotEqual(id(item), id(copied_item))
+ copied_item['name'] = copied_item['name'].upper()
+ self.assertNotEqual(item['name'], copied_item['name'])
+
if __name__ == "__main__":
unittest.main()