itemadapter
Common interface for data container classes
Description
itemadapter
The ItemAdapter class is a wrapper for data container objects, providing a
common interface to handle objects of different types in an uniform manner,
regardless of their underlying implementation.
Currently supported types are:
scrapy.item.Itemdictdataclass-based classesattrs-based classespydantic-based classes
Additionally, interaction with arbitrary types is supported, by implementing
a pre-defined interface (see extending itemadapter).
Requirements
- Python 3.9+, either the CPython implementation (default) or the PyPy implementation
scrapy2.2+: optional, needed to interact withscrapyitemsattrs20.1.0+: optional, needed to interact withattrs-based itemspydantic1.8+: optional, needed to interact withpydantic-based items
Installation
itemadapter is available on PyPI, it can be installed with pip:
pip install itemadapter
For attrs, pydantic and scrapy support, install the corresponding extra
to ensure that a supported version of the corresponding dependencies is
installed. For example:
pip install itemadapter[scrapy]
Mind that you can install multiple extras as needed. For example:
pip install itemadapter[attrs,pydantic,scrapy]
License
itemadapter is distributed under a BSD-3 license.
Basic usage
The following is a simple example using a dataclass object.
Consider the following type definition:
>>> from dataclasses import dataclass
>>> from itemadapter import ItemAdapter
>>> @dataclass
... class InventoryItem:
... name: str
... price: float
... stock: int
>>>
An ItemAdapter object can be treated much like a dictionary:
>>> obj = InventoryItem(name='foo', price=20.5, stock=10)
>>> ItemAdapter.is_item(obj)
True
>>> adapter = ItemAdapter(obj)
>>> len(adapter)
3
>>> adapter["name"]
'foo'
>>> adapter.get("price")
20.5
>>>
The wrapped object is modified in-place:
>>> adapter["name"] = "bar"
>>> adapter.update({"price": 12.7, "stock": 9})
>>> adapter.item
InventoryItem(name='bar', price=12.7, stock=9)
>>> adapter.item is obj
True
>>>
Converting to dict
The ItemAdapter class provides the asdict method, which converts
nested items recursively. Consider the following example:
>>> from dataclasses import dataclass
>>> from itemadapter import ItemAdapter
>>> @dataclass
... class Price:
... value: int
... currency: str
>>> @dataclass
... class Product:
... name: str
... price: Price
>>>
>>> item = Product("Stuff", Price(42, "UYU"))
>>> adapter = ItemAdapter(item)
>>> adapter.asdict()
{'name': 'Stuff', 'price': {'value': 42, 'currency': 'UYU'}}
>>>
Note that just passing an adapter object to the dict built-in also works,
but it doesn't traverse the object recursively converting nested items:
>>> dict(adapter)
{'name': 'Stuff', 'price': Price(value=42, currency='UYU')}
>>>
API reference
Built-in adapters
The following adapters are included by default:
itemadapter.adapter.ScrapyItemAdapter: handlesScrapyitemsitemadapter.adapter.DictAdapter: handlesPythondictionariesitemadapter.adapter.DataclassAdapter: handlesdataclassobjectsitemadapter.adapter.AttrsAdapter: handlesattrsobjectsitemadapter.adapter.PydanticAdapter: handlespydanticobjects
class itemadapter.adapter.ItemAdapter(item: Any)
This is the main entrypoint for the package. Tipically, user code
wraps an item using this class, and proceeds to handle it with the provided interface.
ItemAdapter implements the
MutableMapping
interface, providing a dict-like API to manipulate data for the object it wraps
(which is modified in-place).
Attributes
class attribute ADAPTER_CLASSES: Iterable
Stores the currently registered adapter classes.
The order in which the adapters are registered is important. When an ItemAdapter object is
created for a specific item, the registered adapters are traversed in order and the first
adapter class to return True for the is_item class method is used for all subsequent
operations. The default order is the one defined in the
built-in adapters section.
The default implementation uses a
collections.deque
to support efficient addition/deletion of adapters classes to both ends, but if you are
deriving a subclass (see the section on extending itemadapter
for additional information), any other iterable (e.g. list, tuple) will work.
Methods
class method is_item(item: Any) -> bool
Return True if any of the registed adapters can handle the item
(i.e. if any of them returns True for its is_item method with
item as argument), False otherwise.
class method is_item_class(item_class: type) -> bool
Return True if any of the registered adapters can handle the item class
(i.e. if any of them returns True for its is_item_class method with
item_class as argument), False otherwise.
class method get_field_meta_from_class(item_class: type, field_name: str) -> MappingProxyType
Return a types.MappingProxyType
object, which is a read-only mapping with metadata about the given field. If the item class does not
support field metadata, or there is no metadata for the given field, an empty object is returned.
The returned value is taken from the following sources, depending on the item type:
scrapy.item.Fieldforscrapy.item.Itemsdataclasses.field.metadatafordataclass-based itemsattr.Attribute.metadataforattrs-based itemspydantic.fields.FieldInfoforpydantic-based items
class method get_field_names_from_class(item_class: type) -> Optional[list[str]]
Return a list with the names of all the fields defined for the item class. If an item class doesn't support defining fields upfront, None is returned.
class method get_json_schema(item_class: type) -> dict[str, Any]
Return a dict with a JSON Schema representation of the item class.
The generated JSON Schema reflects field type hints, attribute docstrings and class and field metadata of any supported item class. It also supports using item classes in field types of other item classes.
For example, given:
from dataclasses import dataclass
import attrs
@dataclass
class Brand:
name: str
@attrs.define
class Product:
name: str
"""Product name"""
brand: Brand | None
in_stock: bool = True
ItemAdapter.get_json_schema(Product) returns:
{
"type": "object",
"additionalProperties": False,
"properties": {
"name": {"type": "string", "description": "Product name"},
"brand": {
"anyOf": [
{"type": "null"},
{
"type": "object",
"additionalProperties": False,
"properties": {"name": {"type": "string"}},
"required": ["name"],
},
]
},
"in_stock": {"default": True, "type": "boolean"},
},
"required": ["name", "brand"],
}
You can also extend or override JSON Schema data at the item class or field level:
-
Set
json_schema_extrain field metadata to extend or override the JSON Schema data for that field. For example:>>> from scrapy.item import Item, Field >>> from itemadapter import ItemAdapter >>> class MyItem(Item): ... name: str = Field(json_schema_extra={"minLength": 1}) ... >>> ItemAdapter.get_json_schema(MyItem) {'type': 'object', 'additionalProperties': False, 'properties': {'name': {'minLength': 1, 'type': 'string'}}} -
Define a
__json_schema_extra__class attribute dict to extend or override JSON Schema data for the entire class. For example:>>> from dataclasses import dataclass >>> from itemadapter import ItemAdapter >>> @dataclass ... class MyItem: ... __json_schema_extra__ = {"additionalProperties": True} ... name: str ... >>> ItemAdapter.get_json_schema(MyItem) {'additionalProperties': True, 'type': 'object', 'properties': {'name': {'type': 'string'}}, 'required': ['name']}
Note that, for Pydantic items, itemadapter does not use
model_json_schema()
and instead