1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666
|
# itemadapter
[](https://pypi.python.org/pypi/itemadapter)
[](https://pypi.python.org/pypi/itemadapter)
[](https://github.com/scrapy/itemadapter/actions)
[](https://codecov.io/gh/scrapy/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.Item`](https://docs.scrapy.org/en/latest/topics/items.html#scrapy.item.Item)
* [`dict`](https://docs.python.org/3/library/stdtypes.html#dict)
* [`dataclass`](https://docs.python.org/3/library/dataclasses.html)-based classes
* [`attrs`](https://www.attrs.org)-based classes
* [`pydantic`](https://pydantic-docs.helpmanual.io/)-based classes
Additionally, interaction with arbitrary types is supported, by implementing
a pre-defined interface (see [extending `itemadapter`](#extending-itemadapter)).
---
## Requirements
* Python 3.9+, either the CPython implementation (default) or the PyPy
implementation
* [`scrapy`](https://scrapy.org/) 2.2+: optional, needed to interact with
`scrapy` items
* [`attrs`](https://pypi.org/project/attrs/) 20.1.0+: optional, needed to
interact with `attrs`-based items
* [`pydantic`](https://pypi.org/project/pydantic/) 1.8+: optional, needed to
interact with `pydantic`-based items
---
## Installation
`itemadapter` is available on [`PyPI`](https://pypi.python.org/pypi/itemadapter), 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](https://opensource.org/licenses/BSD-3-Clause) license.
---
## Basic usage
The following is a simple example using a `dataclass` object.
Consider the following type definition:
```python
>>> 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:
```python
>>> 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:
```python
>>> 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:
```python
>>> from dataclasses import dataclass
>>> from itemadapter import ItemAdapter
>>> @dataclass
... class Price:
... value: int
... currency: str
>>> @dataclass
... class Product:
... name: str
... price: Price
>>>
```
```python
>>> 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:
```python
>>> 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`: handles `Scrapy` items
* `itemadapter.adapter.DictAdapter`: handles `Python` dictionaries
* `itemadapter.adapter.DataclassAdapter`: handles `dataclass` objects
* `itemadapter.adapter.AttrsAdapter`: handles `attrs` objects
* `itemadapter.adapter.PydanticAdapter`: handles `pydantic` objects
### 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`](https://docs.python.org/3/library/collections.abc.html#collections.abc.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](#built-in-adapters) section.
The default implementation uses a
[`collections.deque`](https://docs.python.org/3/library/collections.html#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](#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`](https://docs.python.org/3/library/types.html#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.Field`](https://docs.scrapy.org/en/latest/topics/items.html#item-fields)
for `scrapy.item.Item`s
* [`dataclasses.field.metadata`](https://docs.python.org/3/library/dataclasses.html#dataclasses.field)
for `dataclass`-based items
* [`attr.Attribute.metadata`](https://www.attrs.org/en/stable/examples.html#metadata)
for `attrs`-based items
* [`pydantic.fields.FieldInfo`](https://pydantic-docs.helpmanual.io/usage/schema/#field-customisation)
for `pydantic`-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](https://json-schema.org/) 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:
```python
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:
```python
{
"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_extra` in field metadata to extend or override the JSON
Schema data for that field. For example:
```python
>>> 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'}}, 'required': ['name']}
```
- Define a `__json_schema_extra__` class attribute dict to extend or override
JSON Schema data for the entire class. For example:
```python
>>> 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()`](https://docs.pydantic.dev/latest/api/base_model/#pydantic.BaseModel.model_json_schema)
and instead uses its own implementation. That way, the output JSON Schema is
consistent across different item types. It also makes it possible to generate
JSON Schemas for Pydantic models that have nested non-Pydantic item classes as
fields. The downside is that JSON Schema support in itemadapter may not be as
advanced as Pydanticâs.
The following are some known limitations of JSON Schema generation in
itemadapter:
- Attribute docstrings are read with
[`inspect.getsource()`](https://docs.python.org/3/library/inspect.html#inspect.getsource),
and may not be readable at run time in some cases. For such cases, define
`description` within `json_schema_extra` instead (see below).
- String pattern contraints are silently ignored if they are not compatible
with JSON Schema. No effort is made to make them compatible.
- Recursion is silently ignored: if you have an item class that has an
attribute with that same item class as a type or as part of its type, a
simple `{"type": "object"}` is used to map the nested instances of that
item class.
#### `get_field_meta(field_name: str) -> MappingProxyType`
Return metadata for the given field, if available. Unless overriden in a custom adapter class, by default
this method calls the adapter's `get_field_meta_from_class` method, passing the wrapped item's class.
#### `field_names() -> collections.abc.KeysView`
Return a [keys view](https://docs.python.org/3/library/collections.abc.html#collections.abc.KeysView)
with the names of all the defined fields for the item.
#### `asdict() -> dict`
Return a `dict` object with the contents of the adapter. This works slightly different than
calling `dict(adapter)`, because it's applied recursively to nested items (if there are any).
### function `itemadapter.utils.is_item(obj: Any) -> bool`
Return `True` if the given object belongs to (at least) one of the supported types,
`False` otherwise. This is an alias, using the `itemadapter.adapter.ItemAdapter.is_item`
class method is encouraged for better performance.
### function `itemadapter.utils.get_field_meta_from_class(item_class: type, field_name: str) -> types.MappingProxyType`
Alias for `itemadapter.adapter.ItemAdapter.get_field_meta_from_class`
---
## Metadata support
`scrapy.item.Item`, `dataclass`, `attrs`, and `pydantic` objects allow the definition of
arbitrary field metadata. This can be accessed through a
[`MappingProxyType`](https://docs.python.org/3/library/types.html#types.MappingProxyType)
object, which can be retrieved from an item instance with
`itemadapter.adapter.ItemAdapter.get_field_meta`, or from an item class
with the `itemadapter.adapter.ItemAdapter.get_field_meta_from_class`
method (or its alias `itemadapter.utils.get_field_meta_from_class`).
The source of the data depends on the underlying type (see the docs for
`ItemAdapter.get_field_meta_from_class`).
#### `scrapy.item.Item` objects
```python
>>> from scrapy.item import Item, Field
>>> from itemadapter import ItemAdapter
>>> class InventoryItem(Item):
... name = Field(serializer=str)
... value = Field(serializer=int, limit=100)
...
>>> adapter = ItemAdapter(InventoryItem(name="foo", value=10))
>>> adapter.get_field_meta("name")
mappingproxy({'serializer': <class 'str'>})
>>> adapter.get_field_meta("value")
mappingproxy({'serializer': <class 'int'>, 'limit': 100})
>>>
```
#### `dataclass` objects
```python
>>> from dataclasses import dataclass, field
>>> @dataclass
... class InventoryItem:
... name: str = field(metadata={"serializer": str})
... value: int = field(metadata={"serializer": int, "limit": 100})
...
>>> adapter = ItemAdapter(InventoryItem(name="foo", value=10))
>>> adapter.get_field_meta("name")
mappingproxy({'serializer': <class 'str'>})
>>> adapter.get_field_meta("value")
mappingproxy({'serializer': <class 'int'>, 'limit': 100})
>>>
```
#### `attrs` objects
```python
>>> import attr
>>> @attr.s
... class InventoryItem:
... name = attr.ib(metadata={"serializer": str})
... value = attr.ib(metadata={"serializer": int, "limit": 100})
...
>>> adapter = ItemAdapter(InventoryItem(name="foo", value=10))
>>> adapter.get_field_meta("name")
mappingproxy({'serializer': <class 'str'>})
>>> adapter.get_field_meta("value")
mappingproxy({'serializer': <class 'int'>, 'limit': 100})
>>>
```
#### `pydantic` objects
```python
>>> from pydantic import BaseModel, Field
>>> class InventoryItem(BaseModel):
... name: str = Field(json_schema_extra={"serializer": str})
... value: int = Field(json_schema_extra={"serializer": int, "limit": 100})
...
>>> adapter = ItemAdapter(InventoryItem(name="foo", value=10))
>>> adapter.get_field_meta("name")
mappingproxy({'annotation': <class 'str'>, 'json_schema_extra': {'serializer': <class 'str'>}, 'repr': True})
>>> adapter.get_field_meta("value")
mappingproxy({'annotation': <class 'int'>, 'json_schema_extra': {'serializer': <class 'int'>, 'limit': 100}, 'repr': True})
>>>
```
---
## Extending `itemadapter`
This package allows to handle arbitrary item classes, by implementing an adapter interface:
_class `itemadapter.adapter.AdapterInterface(item: Any)`_
Abstract Base Class for adapters. An adapter that handles a specific type of item must
inherit from this class and implement the abstract methods defined on it. `AdapterInterface`
inherits from [`collections.abc.MutableMapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.MutableMapping),
so all methods from the `MutableMapping` interface must be implemented as well.
* _class method `is_item_class(cls, item_class: type) -> bool`_
Return `True` if the adapter can handle the given item class, `False` otherwise. Abstract (mandatory).
* _class method `is_item(cls, item: Any) -> bool`_
Return `True` if the adapter can handle the given item, `False` otherwise.
The default implementation calls `cls.is_item_class(item.__class__)`.
* _class method `get_field_meta_from_class(cls, item_class: type) -> bool`_
Return metadata for the given item class and field name, if available.
By default, this method returns an empty `MappingProxyType` object. Please supply your
own method definition if you want to handle field metadata based on custom logic.
See the [section on metadata support](#metadata-support) for additional information.
* _method `get_field_meta(self, field_name: str) -> types.MappingProxyType`_
Return metadata for the given field name, if available. It's usually not necessary to
override this method, since the `itemadapter.adapter.AdapterInterface` base class
provides a default implementation that calls `ItemAdapter.get_field_meta_from_class`
with the wrapped item's class as argument.
See the [section on metadata support](#metadata-support) for additional information.
* _method `field_names(self) -> collections.abc.KeysView`_:
Return a [dynamic view](https://docs.python.org/3/library/collections.abc.html#collections.abc.KeysView)
of the item's field names. By default, this method returns the result of calling `keys()` on
the current adapter, i.e., its return value depends on the implementation of the methods from the
`MutableMapping` interface (more specifically, it depends on the return value of `__iter__`).
You might want to override this method if you want a way to get all fields for an item, whether or not
they are populated. For instance, Scrapy uses this method to define column names when exporting items to CSV.
### Registering an adapter
Add your custom adapter class to the
`itemadapter.adapter.ItemAdapter.ADAPTER_CLASSES` class attribute in order to
handle custom item classes.
**Example**
```
pip install zyte-common-items
```
```python
>>> from itemadapter.adapter import ItemAdapter
>>> from zyte_common_items import Item, ZyteItemAdapter
>>>
>>> ItemAdapter.ADAPTER_CLASSES.appendleft(ZyteItemAdapter)
>>> item = Item()
>>> adapter = ItemAdapter(item)
>>> adapter
<ItemAdapter for Item()>
>>>
```
### Multiple adapter classes
If you need to have different handlers and/or priorities for different cases
you can subclass the `ItemAdapter` class and set the `ADAPTER_CLASSES`
attribute as needed:
**Example**
```python
>>> from itemadapter.adapter import (
... ItemAdapter,
... AttrsAdapter,
... DataclassAdapter,
... DictAdapter,
... PydanticAdapter,
... ScrapyItemAdapter,
... )
>>> from scrapy.item import Item, Field
>>>
>>> class BuiltinTypesItemAdapter(ItemAdapter):
... ADAPTER_CLASSES = [DictAdapter, DataclassAdapter]
...
>>> class ThirdPartyTypesItemAdapter(ItemAdapter):
... ADAPTER_CLASSES = [AttrsAdapter, PydanticAdapter, ScrapyItemAdapter]
...
>>> class ScrapyItem(Item):
... foo = Field()
...
>>> BuiltinTypesItemAdapter.is_item(dict())
True
>>> ThirdPartyTypesItemAdapter.is_item(dict())
False
>>> BuiltinTypesItemAdapter.is_item(ScrapyItem(foo="bar"))
False
>>> ThirdPartyTypesItemAdapter.is_item(ScrapyItem(foo="bar"))
True
>>>
```
---
## More examples
### `scrapy.item.Item` objects
```python
>>> from scrapy.item import Item, Field
>>> from itemadapter import ItemAdapter
>>> class InventoryItem(Item):
... name = Field()
... price = Field()
...
>>> item = InventoryItem(name="foo", price=10)
>>> adapter = ItemAdapter(item)
>>> adapter.item is item
True
>>> adapter["name"]
'foo'
>>> adapter["name"] = "bar"
>>> adapter["price"] = 5
>>> item
{'name': 'bar', 'price': 5}
>>>
```
### `dict`
```python
>>> from itemadapter import ItemAdapter
>>> item = dict(name="foo", price=10)
>>> adapter = ItemAdapter(item)
>>> adapter.item is item
True
>>> adapter["name"]
'foo'
>>> adapter["name"] = "bar"
>>> adapter["price"] = 5
>>> item
{'name': 'bar', 'price': 5}
>>>
```
### `dataclass` objects
```python
>>> from dataclasses import dataclass
>>> from itemadapter import ItemAdapter
>>> @dataclass
... class InventoryItem:
... name: str
... price: int
...
>>> item = InventoryItem(name="foo", price=10)
>>> adapter = ItemAdapter(item)
>>> adapter.item is item
True
>>> adapter["name"]
'foo'
>>> adapter["name"] = "bar"
>>> adapter["price"] = 5
>>> item
InventoryItem(name='bar', price=5)
>>>
```
### `attrs` objects
```python
>>> import attr
>>> from itemadapter import ItemAdapter
>>> @attr.s
... class InventoryItem:
... name = attr.ib()
... price = attr.ib()
...
>>> item = InventoryItem(name="foo", price=10)
>>> adapter = ItemAdapter(item)
>>> adapter.item is item
True
>>> adapter["name"]
'foo'
>>> adapter["name"] = "bar"
>>> adapter["price"] = 5
>>> item
InventoryItem(name='bar', price=5)
>>>
```
### `pydantic` objects
```python
>>> from pydantic import BaseModel
>>> from itemadapter import ItemAdapter
>>> class InventoryItem(BaseModel):
... name: str
... price: int
...
>>> item = InventoryItem(name="foo", price=10)
>>> adapter = ItemAdapter(item)
>>> adapter.item is item
True
>>> adapter["name"]
'foo'
>>> adapter["name"] = "bar"
>>> adapter["price"] = 5
>>> item
InventoryItem(name='bar', price=5)
>>>
```
## Changelog
See the [full changelog](Changelog.md)
|