Skip to content

Support for Serializing/Deserializing Built-in IP Address Types #1856

@Lemminkyinen

Description

@Lemminkyinen

Description

Will there be support for serializing/deserializing Python's built-in IP addresse types? Currently, they are treated as unknown types.

I am aware of serialize_unknown parameter and it can remedy this particular case, but there can be cases where raising an error for other types is appropriate. It just feels reasonable that Python’s built-in IP address types should be treated as known types and automatically serialized/deserialized to/from strings (as they already have a standard __str__ representation).

my_data: dict[str, Any] = {
    "ipv4": IPv4Address("1.1.1.1"),
    "my_decimal": Decimal(123),
    "more_data": [{"kissa": "koira"}],
    "nested_ip": {"ip": IPv4Address("1.2.2.3")},
}
to_json(my_data)

Raises:

Traceback (most recent call last):
  File "/xx/xx.py", line xx, in <module>
    to_json(my_data)
    ^^^^^^^^^^^^^^^^
pydantic_core._pydantic_core.PydanticSerializationError: Unable to serialize unknown type: <class 'ipaddress.IPv4Address'>

I am aware of serialize_unknown and it remedies this particular case, but there are cases when raising an error is appropriate. I just think that it would be reasonable to consider Python's built-in IP addresses as known types that can be serialized/deserialized.

My solution for now

my_data: dict[str, Any] = {
    "ipv4": IPv4Address("1.1.1.1"),
    "my_decimal": Decimal(123),
    "more_data": [{"kissa": "koira"}],
    "nested_ip": {"ip": IPv4Address("1.2.2.3")},
}
type AnyDict = dict[str, Any | AnyDict | IPvAnyAddress]
adapter: TypeAdapter[AnyDict] = TypeAdapter(AnyDict)
adapter.dump_python(my_data, mode="json")
>>> {'ipv4': '1.1.1.1', 'my_decimal': '123', 'more_data': [{'kissa': 'koira'}], 'nested_ip': {'ip': '1.2.2.3'}}

Version info

             pydantic version: 2.12.3
        pydantic-core version: 2.41.4
          pydantic-core build: profile=release pgo=false
               python version: 3.12.11 (main, Oct  6 2025, 09:15:07) [GCC 13.3.0]
                     platform: Linux-6.14.11-061411-generic-x86_64-with-glibc2.39
             related packages: typing_extensions-4.15.0

Related: pydantic/pydantic#8942
Related: pydantic/pydantic#10559

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions