itemadapter


Nameitemadapter JSON
Version 0.9.0 PyPI version JSON
download
home_pagehttps://github.com/scrapy/itemadapter
SummaryCommon interface for data container classes
upload_time2024-05-07 08:11:00
maintainerNone
docs_urlNone
authorEugenio Lacuesta
requires_python>=3.8
licenseBSD
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # itemadapter
[![version](https://img.shields.io/pypi/v/itemadapter.svg)](https://pypi.python.org/pypi/itemadapter)
[![pyversions](https://img.shields.io/pypi/pyversions/itemadapter.svg)](https://pypi.python.org/pypi/itemadapter)
[![actions](https://github.com/scrapy/itemadapter/workflows/Tests/badge.svg)](https://github.com/scrapy/itemadapter/actions)
[![codecov](https://codecov.io/gh/scrapy/itemadapter/branch/master/graph/badge.svg)](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 (`pydantic>=2` not yet supported)

Additionally, interaction with arbitrary types is supported, by implementing
a pre-defined interface (see [extending `itemadapter`](#extending-itemadapter)).

---

## Requirements

* Python 3.8+
* [`scrapy`](https://scrapy.org/): optional, needed to interact with `scrapy` items
* [`attrs`](https://pypi.org/project/attrs/): optional, needed to interact with `attrs`-based items
* [`pydantic`](https://pypi.org/project/pydantic/): optional, needed to interact with
  `pydantic`-based items (`pydantic>=2` not yet supported)

---

## Installation

`itemadapter` is available on [`PyPI`](https://pypi.python.org/pypi/itemadapter), it can be installed with `pip`:

```
pip install itemadapter
```

---

## 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.

#### `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(serializer=str)
...     value: int = 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})
>>>
```

---

## 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**
```python
>>> from itemadapter.adapter import ItemAdapter
>>> from tests.test_interface import BaseFakeItemAdapter, FakeItemClass
>>>
>>> ItemAdapter.ADAPTER_CLASSES.appendleft(BaseFakeItemAdapter)
>>> item = FakeItemClass()
>>> adapter = ItemAdapter(item)
>>> adapter
<ItemAdapter for FakeItemClass()>
>>>
```

### 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)

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/scrapy/itemadapter",
    "name": "itemadapter",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": null,
    "keywords": null,
    "author": "Eugenio Lacuesta",
    "author_email": "eugenio.lacuesta@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/eb/60/a16c93c9d26e83c05bc6b3edc1a8013025b37ca82dee7eda6f89aec583d3/itemadapter-0.9.0.tar.gz",
    "platform": null,
    "description": "# itemadapter\n[![version](https://img.shields.io/pypi/v/itemadapter.svg)](https://pypi.python.org/pypi/itemadapter)\n[![pyversions](https://img.shields.io/pypi/pyversions/itemadapter.svg)](https://pypi.python.org/pypi/itemadapter)\n[![actions](https://github.com/scrapy/itemadapter/workflows/Tests/badge.svg)](https://github.com/scrapy/itemadapter/actions)\n[![codecov](https://codecov.io/gh/scrapy/itemadapter/branch/master/graph/badge.svg)](https://codecov.io/gh/scrapy/itemadapter)\n\n\nThe `ItemAdapter` class is a wrapper for data container objects, providing a\ncommon interface to handle objects of different types in an uniform manner,\nregardless of their underlying implementation.\n\nCurrently supported types are:\n\n* [`scrapy.item.Item`](https://docs.scrapy.org/en/latest/topics/items.html#scrapy.item.Item)\n* [`dict`](https://docs.python.org/3/library/stdtypes.html#dict)\n* [`dataclass`](https://docs.python.org/3/library/dataclasses.html)-based classes\n* [`attrs`](https://www.attrs.org)-based classes\n* [`pydantic`](https://pydantic-docs.helpmanual.io/)-based classes (`pydantic>=2` not yet supported)\n\nAdditionally, interaction with arbitrary types is supported, by implementing\na pre-defined interface (see [extending `itemadapter`](#extending-itemadapter)).\n\n---\n\n## Requirements\n\n* Python 3.8+\n* [`scrapy`](https://scrapy.org/): optional, needed to interact with `scrapy` items\n* [`attrs`](https://pypi.org/project/attrs/): optional, needed to interact with `attrs`-based items\n* [`pydantic`](https://pypi.org/project/pydantic/): optional, needed to interact with\n  `pydantic`-based items (`pydantic>=2` not yet supported)\n\n---\n\n## Installation\n\n`itemadapter` is available on [`PyPI`](https://pypi.python.org/pypi/itemadapter), it can be installed with `pip`:\n\n```\npip install itemadapter\n```\n\n---\n\n## License\n\n`itemadapter` is distributed under a [BSD-3](https://opensource.org/licenses/BSD-3-Clause) license.\n\n---\n\n## Basic usage\n\nThe following is a simple example using a `dataclass` object.\nConsider the following type definition:\n\n```python\n>>> from dataclasses import dataclass\n>>> from itemadapter import ItemAdapter\n>>> @dataclass\n... class InventoryItem:\n...     name: str\n...     price: float\n...     stock: int\n>>>\n```\n\nAn `ItemAdapter` object can be treated much like a dictionary:\n\n```python\n>>> obj = InventoryItem(name='foo', price=20.5, stock=10)\n>>> ItemAdapter.is_item(obj)\nTrue\n>>> adapter = ItemAdapter(obj)\n>>> len(adapter)\n3\n>>> adapter[\"name\"]\n'foo'\n>>> adapter.get(\"price\")\n20.5\n>>>\n```\n\nThe wrapped object is modified in-place:\n```python\n>>> adapter[\"name\"] = \"bar\"\n>>> adapter.update({\"price\": 12.7, \"stock\": 9})\n>>> adapter.item\nInventoryItem(name='bar', price=12.7, stock=9)\n>>> adapter.item is obj\nTrue\n>>>\n```\n\n### Converting to dict\n\nThe `ItemAdapter` class provides the `asdict` method, which converts\nnested items recursively. Consider the following example:\n\n```python\n>>> from dataclasses import dataclass\n>>> from itemadapter import ItemAdapter\n>>> @dataclass\n... class Price:\n...     value: int\n...     currency: str\n>>> @dataclass\n... class Product:\n...     name: str\n...     price: Price\n>>>\n```\n\n```python\n>>> item = Product(\"Stuff\", Price(42, \"UYU\"))\n>>> adapter = ItemAdapter(item)\n>>> adapter.asdict()\n{'name': 'Stuff', 'price': {'value': 42, 'currency': 'UYU'}}\n>>>\n```\n\nNote that just passing an adapter object to the `dict` built-in also works,\nbut it doesn't traverse the object recursively converting nested items:\n\n```python\n>>> dict(adapter)\n{'name': 'Stuff', 'price': Price(value=42, currency='UYU')}\n>>>\n```\n\n---\n\n## API reference\n\n### Built-in adapters\n\nThe following adapters are included by default:\n\n* `itemadapter.adapter.ScrapyItemAdapter`: handles `Scrapy` items\n* `itemadapter.adapter.DictAdapter`: handles `Python` dictionaries\n* `itemadapter.adapter.DataclassAdapter`: handles `dataclass` objects\n* `itemadapter.adapter.AttrsAdapter`: handles `attrs` objects\n* `itemadapter.adapter.PydanticAdapter`: handles `pydantic` objects\n\n### class `itemadapter.adapter.ItemAdapter(item: Any)`\n\nThis is the main entrypoint for the package. Tipically, user code\nwraps an item using this class, and proceeds to handle it with the provided interface.\n`ItemAdapter` implements the\n[`MutableMapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.MutableMapping)\ninterface, providing a `dict`-like API to manipulate data for the object it wraps\n(which is modified in-place).\n\n**Attributes**\n\n#### class attribute `ADAPTER_CLASSES: Iterable`\n\nStores the currently registered adapter classes.\n\nThe order in which the adapters are registered is important. When an `ItemAdapter` object is\ncreated for a specific item, the registered adapters are traversed in order and the first\nadapter class to return `True` for the `is_item` class method is used for all subsequent\noperations. The default order is the one defined in the\n[built-in adapters](#built-in-adapters) section.\n\nThe default implementation uses a\n[`collections.deque`](https://docs.python.org/3/library/collections.html#collections.deque)\nto support efficient addition/deletion of adapters classes to both ends, but if you are\nderiving a subclass (see the section on [extending itemadapter](#extending-itemadapter)\nfor additional information), any other iterable (e.g. `list`, `tuple`) will work.\n\n**Methods**\n\n#### class method `is_item(item: Any) -> bool`\n\nReturn `True` if any of the registed adapters can handle the item\n(i.e. if any of them returns `True` for its `is_item` method with\n`item` as argument), `False` otherwise.\n\n#### class method `is_item_class(item_class: type) -> bool`\n\nReturn `True` if any of the registered adapters can handle the item class\n(i.e. if any of them returns `True` for its `is_item_class` method with\n`item_class` as argument), `False` otherwise.\n\n#### class method `get_field_meta_from_class(item_class: type, field_name: str) -> MappingProxyType`\n\nReturn a [`types.MappingProxyType`](https://docs.python.org/3/library/types.html#types.MappingProxyType)\nobject, which is a read-only mapping with metadata about the given field. If the item class does not\nsupport field metadata, or there is no metadata for the given field, an empty object is returned.\n\nThe returned value is taken from the following sources, depending on the item type:\n\n  * [`scrapy.item.Field`](https://docs.scrapy.org/en/latest/topics/items.html#item-fields)\n    for `scrapy.item.Item`s\n  * [`dataclasses.field.metadata`](https://docs.python.org/3/library/dataclasses.html#dataclasses.field)\n    for `dataclass`-based items\n  * [`attr.Attribute.metadata`](https://www.attrs.org/en/stable/examples.html#metadata)\n    for `attrs`-based items\n  * [`pydantic.fields.FieldInfo`](https://pydantic-docs.helpmanual.io/usage/schema/#field-customisation)\n    for `pydantic`-based items\n\n#### class method `get_field_names_from_class(item_class: type) -> Optional[list[str]]`\n\nReturn a list with the names of all the fields defined for the item class.\nIf an item class doesn't support defining fields upfront, None is returned.\n\n#### `get_field_meta(field_name: str) -> MappingProxyType`\n\nReturn metadata for the given field, if available. Unless overriden in a custom adapter class, by default\nthis method calls the adapter's `get_field_meta_from_class` method, passing the wrapped item's class.\n\n#### `field_names() -> collections.abc.KeysView`\n\nReturn a [keys view](https://docs.python.org/3/library/collections.abc.html#collections.abc.KeysView)\nwith the names of all the defined fields for the item.\n\n#### `asdict() -> dict`\n\nReturn a `dict` object with the contents of the adapter. This works slightly different than\ncalling `dict(adapter)`, because it's applied recursively to nested items (if there are any).\n\n\n### function `itemadapter.utils.is_item(obj: Any) -> bool`\n\nReturn `True` if the given object belongs to (at least) one of the supported types,\n`False` otherwise. This is an alias, using the `itemadapter.adapter.ItemAdapter.is_item`\nclass method is encouraged for better performance.\n\n\n### function `itemadapter.utils.get_field_meta_from_class(item_class: type, field_name: str) -> types.MappingProxyType`\n\nAlias for `itemadapter.adapter.ItemAdapter.get_field_meta_from_class`\n\n---\n\n## Metadata support\n\n`scrapy.item.Item`, `dataclass`, `attrs`, and `pydantic` objects allow the definition of\narbitrary field metadata. This can be accessed through a\n[`MappingProxyType`](https://docs.python.org/3/library/types.html#types.MappingProxyType)\nobject, which can be retrieved from an item instance with\n`itemadapter.adapter.ItemAdapter.get_field_meta`, or from an item class\nwith the `itemadapter.adapter.ItemAdapter.get_field_meta_from_class`\nmethod (or its alias `itemadapter.utils.get_field_meta_from_class`).\nThe source of the data depends on the underlying type (see the docs for\n`ItemAdapter.get_field_meta_from_class`).\n\n#### `scrapy.item.Item` objects\n\n```python\n>>> from scrapy.item import Item, Field\n>>> from itemadapter import ItemAdapter\n>>> class InventoryItem(Item):\n...     name = Field(serializer=str)\n...     value = Field(serializer=int, limit=100)\n...\n>>> adapter = ItemAdapter(InventoryItem(name=\"foo\", value=10))\n>>> adapter.get_field_meta(\"name\")\nmappingproxy({'serializer': <class 'str'>})\n>>> adapter.get_field_meta(\"value\")\nmappingproxy({'serializer': <class 'int'>, 'limit': 100})\n>>>\n```\n\n#### `dataclass` objects\n\n```python\n>>> from dataclasses import dataclass, field\n>>> @dataclass\n... class InventoryItem:\n...     name: str = field(metadata={\"serializer\": str})\n...     value: int = field(metadata={\"serializer\": int, \"limit\": 100})\n...\n>>> adapter = ItemAdapter(InventoryItem(name=\"foo\", value=10))\n>>> adapter.get_field_meta(\"name\")\nmappingproxy({'serializer': <class 'str'>})\n>>> adapter.get_field_meta(\"value\")\nmappingproxy({'serializer': <class 'int'>, 'limit': 100})\n>>>\n```\n\n#### `attrs` objects\n\n```python\n>>> import attr\n>>> @attr.s\n... class InventoryItem:\n...     name = attr.ib(metadata={\"serializer\": str})\n...     value = attr.ib(metadata={\"serializer\": int, \"limit\": 100})\n...\n>>> adapter = ItemAdapter(InventoryItem(name=\"foo\", value=10))\n>>> adapter.get_field_meta(\"name\")\nmappingproxy({'serializer': <class 'str'>})\n>>> adapter.get_field_meta(\"value\")\nmappingproxy({'serializer': <class 'int'>, 'limit': 100})\n>>>\n```\n\n#### `pydantic` objects\n\n```python\n>>> from pydantic import BaseModel, Field\n>>> class InventoryItem(BaseModel):\n...     name: str = Field(serializer=str)\n...     value: int = Field(serializer=int, limit=100)\n...\n>>> adapter = ItemAdapter(InventoryItem(name=\"foo\", value=10))\n>>> adapter.get_field_meta(\"name\")\nmappingproxy({'serializer': <class 'str'>})\n>>> adapter.get_field_meta(\"value\")\nmappingproxy({'serializer': <class 'int'>, 'limit': 100})\n>>>\n```\n\n---\n\n## Extending `itemadapter`\n\nThis package allows to handle arbitrary item classes, by implementing an adapter interface:\n\n_class `itemadapter.adapter.AdapterInterface(item: Any)`_\n\nAbstract Base Class for adapters. An adapter that handles a specific type of item must\ninherit from this class and implement the abstract methods defined on it. `AdapterInterface`\ninherits from [`collections.abc.MutableMapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.MutableMapping),\nso all methods from the `MutableMapping` interface must be implemented as well.\n\n* _class method `is_item_class(cls, item_class: type) -> bool`_\n\n    Return `True` if the adapter can handle the given item class, `False` otherwise. Abstract (mandatory).\n\n* _class method `is_item(cls, item: Any) -> bool`_\n\n    Return `True` if the adapter can handle the given item, `False` otherwise.\n    The default implementation calls `cls.is_item_class(item.__class__)`.\n\n* _class method `get_field_meta_from_class(cls, item_class: type) -> bool`_\n\n    Return metadata for the given item class and field name, if available.\n    By default, this method returns an empty `MappingProxyType` object. Please supply your\n    own method definition if you want to handle field metadata based on custom logic.\n    See the [section on metadata support](#metadata-support) for additional information.\n\n* _method `get_field_meta(self, field_name: str) -> types.MappingProxyType`_\n\n    Return metadata for the given field name, if available. It's usually not necessary to\n    override this method, since the `itemadapter.adapter.AdapterInterface` base class\n    provides a default implementation that calls `ItemAdapter.get_field_meta_from_class`\n    with the wrapped item's class as argument.\n    See the [section on metadata support](#metadata-support) for additional information.\n\n* _method `field_names(self) -> collections.abc.KeysView`_:\n\n    Return a [dynamic view](https://docs.python.org/3/library/collections.abc.html#collections.abc.KeysView)\n    of the item's field names. By default, this method returns the result of calling `keys()` on\n    the current adapter, i.e., its return value depends on the implementation of the methods from the\n    `MutableMapping` interface (more specifically, it depends on the return value of `__iter__`).\n\n    You might want to override this method if you want a way to get all fields for an item, whether or not\n    they are populated. For instance, Scrapy uses this method to define column names when exporting items to CSV.\n\n### Registering an adapter\n\nAdd your custom adapter class to the `itemadapter.adapter.ItemAdapter.ADAPTER_CLASSES`\nclass attribute in order to handle custom item classes:\n\n**Example**\n```python\n>>> from itemadapter.adapter import ItemAdapter\n>>> from tests.test_interface import BaseFakeItemAdapter, FakeItemClass\n>>>\n>>> ItemAdapter.ADAPTER_CLASSES.appendleft(BaseFakeItemAdapter)\n>>> item = FakeItemClass()\n>>> adapter = ItemAdapter(item)\n>>> adapter\n<ItemAdapter for FakeItemClass()>\n>>>\n```\n\n### Multiple adapter classes\n\nIf you need to have different handlers and/or priorities for different cases\nyou can subclass the `ItemAdapter` class and set the `ADAPTER_CLASSES`\nattribute as needed:\n\n\n**Example**\n```python\n>>> from itemadapter.adapter import (\n...     ItemAdapter,\n...     AttrsAdapter,\n...     DataclassAdapter,\n...     DictAdapter,\n...     PydanticAdapter,\n...     ScrapyItemAdapter,\n... )\n>>> from scrapy.item import Item, Field\n>>>\n>>> class BuiltinTypesItemAdapter(ItemAdapter):\n...     ADAPTER_CLASSES = [DictAdapter, DataclassAdapter]\n...\n>>> class ThirdPartyTypesItemAdapter(ItemAdapter):\n...     ADAPTER_CLASSES = [AttrsAdapter, PydanticAdapter, ScrapyItemAdapter]\n...\n>>> class ScrapyItem(Item):\n...     foo = Field()\n...\n>>> BuiltinTypesItemAdapter.is_item(dict())\nTrue\n>>> ThirdPartyTypesItemAdapter.is_item(dict())\nFalse\n>>> BuiltinTypesItemAdapter.is_item(ScrapyItem(foo=\"bar\"))\nFalse\n>>> ThirdPartyTypesItemAdapter.is_item(ScrapyItem(foo=\"bar\"))\nTrue\n>>>\n```\n\n---\n\n## More examples\n\n### `scrapy.item.Item` objects\n\n```python\n>>> from scrapy.item import Item, Field\n>>> from itemadapter import ItemAdapter\n>>> class InventoryItem(Item):\n...     name = Field()\n...     price = Field()\n...\n>>> item = InventoryItem(name=\"foo\", price=10)\n>>> adapter = ItemAdapter(item)\n>>> adapter.item is item\nTrue\n>>> adapter[\"name\"]\n'foo'\n>>> adapter[\"name\"] = \"bar\"\n>>> adapter[\"price\"] = 5\n>>> item\n{'name': 'bar', 'price': 5}\n>>>\n```\n\n### `dict`\n\n```python\n>>> from itemadapter import ItemAdapter\n>>> item = dict(name=\"foo\", price=10)\n>>> adapter = ItemAdapter(item)\n>>> adapter.item is item\nTrue\n>>> adapter[\"name\"]\n'foo'\n>>> adapter[\"name\"] = \"bar\"\n>>> adapter[\"price\"] = 5\n>>> item\n{'name': 'bar', 'price': 5}\n>>>\n```\n\n### `dataclass` objects\n\n```python\n>>> from dataclasses import dataclass\n>>> from itemadapter import ItemAdapter\n>>> @dataclass\n... class InventoryItem:\n...     name: str\n...     price: int\n...\n>>> item = InventoryItem(name=\"foo\", price=10)\n>>> adapter = ItemAdapter(item)\n>>> adapter.item is item\nTrue\n>>> adapter[\"name\"]\n'foo'\n>>> adapter[\"name\"] = \"bar\"\n>>> adapter[\"price\"] = 5\n>>> item\nInventoryItem(name='bar', price=5)\n>>>\n```\n\n### `attrs` objects\n\n```python\n>>> import attr\n>>> from itemadapter import ItemAdapter\n>>> @attr.s\n... class InventoryItem:\n...     name = attr.ib()\n...     price = attr.ib()\n...\n>>> item = InventoryItem(name=\"foo\", price=10)\n>>> adapter = ItemAdapter(item)\n>>> adapter.item is item\nTrue\n>>> adapter[\"name\"]\n'foo'\n>>> adapter[\"name\"] = \"bar\"\n>>> adapter[\"price\"] = 5\n>>> item\nInventoryItem(name='bar', price=5)\n>>>\n```\n\n### `pydantic` objects\n\n```python\n>>> from pydantic import BaseModel\n>>> from itemadapter import ItemAdapter\n>>> class InventoryItem(BaseModel):\n...     name: str\n...     price: int\n...\n>>> item = InventoryItem(name=\"foo\", price=10)\n>>> adapter = ItemAdapter(item)\n>>> adapter.item is item\nTrue\n>>> adapter[\"name\"]\n'foo'\n>>> adapter[\"name\"] = \"bar\"\n>>> adapter[\"price\"] = 5\n>>> item\nInventoryItem(name='bar', price=5)\n>>>\n```\n\n\n## Changelog\n\nSee the [full changelog](Changelog.md)\n",
    "bugtrack_url": null,
    "license": "BSD",
    "summary": "Common interface for data container classes",
    "version": "0.9.0",
    "project_urls": {
        "Homepage": "https://github.com/scrapy/itemadapter"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "399371cd02a96887da62e248647da70af60bf1538bbe445b4a0735f84126fc46",
                "md5": "0d7cc20dfb1256ded3b0d205932b8c3e",
                "sha256": "cfd108c9d5205d056fcac402ec8f8e9d799ce9066911eec1cd521ea442f87af1"
            },
            "downloads": -1,
            "filename": "itemadapter-0.9.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "0d7cc20dfb1256ded3b0d205932b8c3e",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 11106,
            "upload_time": "2024-05-07T08:10:59",
            "upload_time_iso_8601": "2024-05-07T08:10:59.263552Z",
            "url": "https://files.pythonhosted.org/packages/39/93/71cd02a96887da62e248647da70af60bf1538bbe445b4a0735f84126fc46/itemadapter-0.9.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "eb60a16c93c9d26e83c05bc6b3edc1a8013025b37ca82dee7eda6f89aec583d3",
                "md5": "9a2007a96edc40bfd9449b00f4597489",
                "sha256": "e4f958a6b6b6f5831fa207373010031a0bd7ed0429ddd09b51979c011475cafd"
            },
            "downloads": -1,
            "filename": "itemadapter-0.9.0.tar.gz",
            "has_sig": false,
            "md5_digest": "9a2007a96edc40bfd9449b00f4597489",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 18922,
            "upload_time": "2024-05-07T08:11:00",
            "upload_time_iso_8601": "2024-05-07T08:11:00.597060Z",
            "url": "https://files.pythonhosted.org/packages/eb/60/a16c93c9d26e83c05bc6b3edc1a8013025b37ca82dee7eda6f89aec583d3/itemadapter-0.9.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-05-07 08:11:00",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "scrapy",
    "github_project": "itemadapter",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "tox": true,
    "lcname": "itemadapter"
}
        
Elapsed time: 0.28756s