Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: use walled garden #31

Merged
merged 1 commit into from
Nov 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/dataclassish/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
"""

from . import converters
from ._core import DataclassInstance, F, asdict, astuple, fields, replace
from ._ext import field_items, field_keys, field_values
from ._src.core import DataclassInstance, F, asdict, astuple, fields, replace
from ._src.ext import field_items, field_keys, field_values
from ._version import version as __version__

__all__ = [
Expand Down
3 changes: 3 additions & 0 deletions src/dataclassish/_src/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
"""Dataclassish."""

__all__: list[str] = []
141 changes: 141 additions & 0 deletions src/dataclassish/_src/converters.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
"""Converters for dataclass fields.

While `dataclasses.field` itself does not allow for converters (See PEP 712)
many dataclasses-like libraries do. A very short, very non-exhaustive list
includes: ``attrs`` and ``equinox``. This module provides a few useful converter
functions. If you need more, check out ``attrs``!

"""
# ruff:noqa: N801
# pylint: disable=C0103

__all__ = ["AbstractConverter", "Optional", "Unless"]

import dataclasses
from abc import ABCMeta, abstractmethod
from collections.abc import Callable
from typing import Any, Generic, TypeVar, cast, overload

ArgT = TypeVar("ArgT") # Input type
RetT = TypeVar("RetT") # Return type


class AbstractConverter(Generic[ArgT, RetT], metaclass=ABCMeta):
"""Abstract converter class."""

converter: Callable[[ArgT], RetT]
"""The converter to apply to the input value."""

@abstractmethod
def __call__(self, value: ArgT, /) -> Any:
"""Convert the input value to the desired output type."""
raise NotImplementedError # pragma: no cover


# -------------------------------------------------------------------


@dataclasses.dataclass(frozen=True, slots=True, eq=False)
class Optional(AbstractConverter[ArgT, RetT]):
"""Optional converter with a defined sentinel value.

This converter allows for a field to be optional, i.e., it can be set to
`None`. This is useful when a field is required in some contexts but not in
others.

This converter is based on ``attr.converters.optional``. If ``attrs`` ever
separates this out into its own package, so that other libraries, like
``equinox``, can use the converter without depending on ``attrs``, then this
implementation will probably be removed.

Examples
--------
For this example we will use ``attrs`` as the dataclass library, but this
converter can be used with any dataclass-like library that supports
converters.

>>> from attrs import define, field
>>> from dataclassish.converters import Optional

>>> @define
... class Class:
... attr: int | None = field(default=None, converter=Optional(int))

>>> obj = Class()
>>> print(obj.attr)
None

>>> obj = Class(1)
>>> obj.attr
1

"""

converter: Callable[[ArgT], RetT]
"""The converter to apply to the input value."""

@overload
def __call__(self, value: None, /) -> None: ...

@overload
def __call__(self, value: ArgT, /) -> RetT: ...

def __call__(self, value: ArgT | None, /) -> RetT | None:
"""Convert the input value to the output type, passing through `None`."""
return None if value is None else self.converter(value)


# -------------------------------------------------------------------

PassThroughTs = TypeVar("PassThroughTs")


@dataclasses.dataclass(frozen=True, slots=True, eq=False)
class Unless(AbstractConverter[ArgT, RetT], Generic[ArgT, PassThroughTs, RetT]):
"""Converter that is applied if the argument is NOT a specified type.

This converter is useful when you want to pass through a value if it is of a
certain type, but convert it otherwise.

Examples
--------
For this example we will use ``attrs`` as the dataclass library, but this
converter can be used with any dataclass-like library that supports
converters.

>>> from attrs import define, field
>>> from dataclassish.converters import Unless

>>> @define
... class Class:
... attr: float | int = field(converter=Unless(int, converter=float))

>>> obj = Class(1)
>>> obj.attr
1

>>> obj = Class("1")
>>> obj.attr
1.0

"""

unconverted_types: type[PassThroughTs] | tuple[type[PassThroughTs], ...]
"""The types to pass through without conversion."""

converter: Callable[[ArgT], RetT]
"""The converter to apply to the input value."""

@overload
def __call__(self, value: ArgT, /) -> RetT: ...

@overload
def __call__(self, value: PassThroughTs, /) -> PassThroughTs: ...

def __call__(self, value: ArgT | PassThroughTs, /) -> RetT | PassThroughTs:
"""Pass through the input value."""
return (
cast(PassThroughTs, value)
if isinstance(value, self.unconverted_types)
else self.converter(cast(ArgT, value))
)
File renamed without changes.
2 changes: 1 addition & 1 deletion src/dataclassish/_ext.py → src/dataclassish/_src/ext.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

from plum import dispatch

from ._core import fields
from .core import fields

K = TypeVar("K")
V = TypeVar("V")
Expand Down
131 changes: 1 addition & 130 deletions src/dataclassish/converters.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,136 +6,7 @@
functions. If you need more, check out ``attrs``!

"""
# ruff:noqa: N801
# pylint: disable=C0103

__all__ = ["AbstractConverter", "Optional", "Unless"]

import dataclasses
from abc import ABCMeta, abstractmethod
from collections.abc import Callable
from typing import Any, Generic, TypeVar, cast, overload

ArgT = TypeVar("ArgT") # Input type
RetT = TypeVar("RetT") # Return type


class AbstractConverter(Generic[ArgT, RetT], metaclass=ABCMeta):
"""Abstract converter class."""

converter: Callable[[ArgT], RetT]
"""The converter to apply to the input value."""

@abstractmethod
def __call__(self, value: ArgT, /) -> Any:
"""Convert the input value to the desired output type."""
raise NotImplementedError # pragma: no cover


# -------------------------------------------------------------------


@dataclasses.dataclass(frozen=True, slots=True, eq=False)
class Optional(AbstractConverter[ArgT, RetT]):
"""Optional converter with a defined sentinel value.

This converter allows for a field to be optional, i.e., it can be set to
`None`. This is useful when a field is required in some contexts but not in
others.

This converter is based on ``attr.converters.optional``. If ``attrs`` ever
separates this out into its own package, so that other libraries, like
``equinox``, can use the converter without depending on ``attrs``, then this
implementation will probably be removed.

Examples
--------
For this example we will use ``attrs`` as the dataclass library, but this
converter can be used with any dataclass-like library that supports
converters.

>>> from attrs import define, field
>>> from dataclassish.converters import Optional

>>> @define
... class Class:
... attr: int | None = field(default=None, converter=Optional(int))

>>> obj = Class()
>>> print(obj.attr)
None

>>> obj = Class(1)
>>> obj.attr
1

"""

converter: Callable[[ArgT], RetT]
"""The converter to apply to the input value."""

@overload
def __call__(self, value: None, /) -> None: ...

@overload
def __call__(self, value: ArgT, /) -> RetT: ...

def __call__(self, value: ArgT | None, /) -> RetT | None:
"""Convert the input value to the output type, passing through `None`."""
return None if value is None else self.converter(value)


# -------------------------------------------------------------------

PassThroughTs = TypeVar("PassThroughTs")


@dataclasses.dataclass(frozen=True, slots=True, eq=False)
class Unless(AbstractConverter[ArgT, RetT], Generic[ArgT, PassThroughTs, RetT]):
"""Converter that is applied if the argument is NOT a specified type.

This converter is useful when you want to pass through a value if it is of a
certain type, but convert it otherwise.

Examples
--------
For this example we will use ``attrs`` as the dataclass library, but this
converter can be used with any dataclass-like library that supports
converters.

>>> from attrs import define, field
>>> from dataclassish.converters import Unless

>>> @define
... class Class:
... attr: float | int = field(converter=Unless(int, converter=float))

>>> obj = Class(1)
>>> obj.attr
1

>>> obj = Class("1")
>>> obj.attr
1.0

"""

unconverted_types: type[PassThroughTs] | tuple[type[PassThroughTs], ...]
"""The types to pass through without conversion."""

converter: Callable[[ArgT], RetT]
"""The converter to apply to the input value."""

@overload
def __call__(self, value: ArgT, /) -> RetT: ...

@overload
def __call__(self, value: PassThroughTs, /) -> PassThroughTs: ...

def __call__(self, value: ArgT | PassThroughTs, /) -> RetT | PassThroughTs:
"""Pass through the input value."""
return (
cast(PassThroughTs, value)
if isinstance(value, self.unconverted_types)
else self.converter(cast(ArgT, value))
)
from ._src.converters import AbstractConverter, Optional, Unless
4 changes: 2 additions & 2 deletions uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.