Skip to content

Commit

Permalink
Docs and docstrings
Browse files Browse the repository at this point in the history
  • Loading branch information
levsh committed Jan 12, 2025
1 parent 77bd2f6 commit 2695e11
Show file tree
Hide file tree
Showing 13 changed files with 486 additions and 38 deletions.
23 changes: 22 additions & 1 deletion cwtch/config.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,35 @@
from typing import Literal


SHOW_INPUT_VALUE_ON_ERROR: bool = True
"""Show input value on ValidationError."""

SLOTS: bool = False
"""Default value for 'slots' argument in dataclass decorator."""

KW_ONLY: bool = False
"""Default value for 'kw_only' argument in dataclass diecorator."""

VALIDATE: bool = True
"""Default value for 'validate' argument in dataclass decorator."""

ADD_DISABLE_VALIDATION_TO_INIT: bool = False
SHOW_INPUT_VALUE_ON_ERROR: bool = True
"""Default value for 'add_disable_validation_to_init' argument in dataclass decorator."""

EXTRA: Literal["ignore", "forbid"] = "ignore"
"""Default value for 'extra' argument in dataclass decorator."""

REPR: bool = True
"""Default value for 'repr' argument in dataclass decorator."""

EQ: bool = True
"""Default value for 'eq' argument in dataclass decorator."""

ATTACH: bool = True
"""Default value for 'attach' argument in view decorator."""

RECURSIVE: bool = True
"""Default value for 'recursive' argument in dataclass decorator."""

HANDLE_CIRCULAR_REFS: bool = False
"""Default value for 'handle_circular_refs' argument in dataclass decorator."""
66 changes: 50 additions & 16 deletions cwtch/cwtch.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,8 @@ def __init__(
metadata: Unset[dict] = UNSET,
kw_only: Unset[bool] = UNSET,
):
if default is not _MISSING and default_factory is not _MISSING:
raise ValueError("cannot specify both default and default_factory")
self.name: str = cast(str, None)
self.type: Any = cast(Any, None)
self.default: Any = default
Expand Down Expand Up @@ -173,7 +175,7 @@ def __eq__(self, other) -> bool:


def field(
default=_MISSING,
default: Any = _MISSING,
*,
default_factory: _Missing[Callable] = _MISSING,
init: bool = True,
Expand All @@ -185,6 +187,22 @@ def field(
metadata: Unset[dict] = UNSET,
kw_only: Unset[dict] = UNSET,
) -> Any:
"""
Return an object to identify dataclass fields.
Args:
default: The default value of the field.
default_factory: A 0-argument function called to initialize a field's value.
init: If init is true, the field will be a parameter to the class's `__init__()` function.
repr: If repr is true, the field will be included in the object's repr().
compare: If compare is true, the field will be used in comparison functions.
property:
validate:
metadata: If specified, must be a mapping which is stored but not otherwise examined by dataclass.
kw_only: If kw_only true, the field will become a keyword-only parameter to `__init__()`.
It is an error to specify both default and default_factory.
"""
return Field(
default=default,
default_factory=default_factory,
Expand Down Expand Up @@ -221,18 +239,18 @@ def dataclass(
) -> Callable[[Type[T]], Type[T]]:
"""
Args:
slots: If true, __slots__ attribute will be generated
slots: If true, `__slots__` attribute will be generated
and new class will be returned instead of the original one.
If __slots__ is already defined in the class, then TypeError is raised.
If `__slots__` is already defined in the class, then TypeError is raised.
kw_only: If kw_only is true, then by default all fields are keyword-only.
env_prefix: Prefix(or list of prefixes) for environment variables.
env_source: Environment variables source factory.
env_source: Environment variables source factory. By default os.environ.
validate: Validate or not fields.
add_disable_validation_to_init: Add `disable_validation` keywoard argument to __init__ method
add_disable_validation_to_init: Add disable_validation keywoard argument to `__init__()` method
to disable validation.
extra: Ignore or forbid extra arguments passed to init.
repr: If true, a __rich_repr__ method will be generated and rich.repr.auto decorator applied to the class.
eq: If true, an __eq__ method will be generated.
repr: If true, a `__rich_repr__()` method will be generated and rich.repr.auto decorator applied to the class.
eq: If true, an `__eq__()` method will be generated.
This method compares the class as if it were a tuple of its fields, in order.
Both instances in the comparison must be of the identical type.
recursive: ...
Expand Down Expand Up @@ -304,7 +322,7 @@ def wrapper(
@dataclass_transform(field_specifiers=(field,))
def view(
base_cls,
name=UNSET,
name: Unset[str] = UNSET,
*,
attach: Unset[bool] = UNSET,
include: Unset[Sequence[str]] = UNSET,
Expand All @@ -327,9 +345,9 @@ def view(
attach: If true, view will be attached to base cls.
include: List of fields to include in view.
exclude: List of fields to exclude from view.
slots: If true, __slots__ attribute will be generated
slots: If true, `__slots__` attribute will be generated
and new class will be returned instead of the original one.
If __slots__ is already defined in the class, then TypeError is raised.
If `__slots__` is already defined in the class, then TypeError is raised.
If UNSET value from base view model will be used.
kw_only: If kw_only is true, then by default all fields are keyword-only.
env_prefix: Prefix(or list of prefixes) for environment variables.
Expand All @@ -338,14 +356,14 @@ def view(
If UNSET value from base view model will be used.
validate: Validate or not fields.
If UNSET value from base view model will be used.
add_disable_validation_to_init: Add `disable_validation` keywoard argument to __init__ method
add_disable_validation_to_init: Add disable_validation keywoard argument to `__init__()` method
to disable validation.
If UNSET value from base view model will be used.
extra: Ignore or forbid extra arguments passed to init.
If UNSET value from base view model will be used.
repr: If true, a __rich_repr__ method will be generated and rich.repr.auto decorator applied to the class.
repr: If true, a `__rich_repr__()` method will be generated and rich.repr.auto decorator applied to the class.
If UNSET value from base view model will be used.
eq: If true, an __eq__ method will be generated.
eq: If true, an `__eq__()` method will be generated.
This method compares the class as if it were a tuple of its fields, in order.
Both instances in the comparison must be of the identical type.
If UNSET value from base view model will be used.
Expand Down Expand Up @@ -1512,7 +1530,7 @@ def cwtch_rebuild(view_cls):

def from_attributes(
cls,
obj,
obj: Any,
data: dict | None = None,
exclude: Sequence | None = None,
suffix: str | None = None,
Expand Down Expand Up @@ -1558,7 +1576,17 @@ def asdict(
exclude_unset: bool | None = None,
context: dict | None = None,
) -> dict:
"""Return `cwtch` model as dict."""
"""
Return cwtch model as dict.
Args:
inst: cwtch model.
include: List of field names to include.
exclude: List of field names to exclude.
exclude_none: If true, fields with None value will be excluded.
exclude_unset: If true, unset fields will be excluded.
context: If specified, must be a mapping.
"""

return _asdict(
inst,
Expand All @@ -1574,7 +1602,13 @@ def asdict(


def dumps_json(inst, encoder: Callable[[Any], Any] | None = None, context: dict | None = None):
"""Dump `cwtch` model to json."""
"""
Dump cwtch model to json.
Args:
encoder: Custom JSON encoder as callable.
context: If specified, must be a mapping.
"""

return _dumps_json(inst, encoder, context)

Expand Down
4 changes: 4 additions & 0 deletions cwtch/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ def __str__(self):
show_value = SHOW_INPUT_VALUE_ON_ERROR
sub_errors_show_value = show_value and len(self.errors) == 1
show_value = show_value and (len(self.errors) > 1 or not isinstance(self.errors[0], ValidationError))

errors = "\n".join(
[
indent(
Expand Down Expand Up @@ -96,3 +97,6 @@ def __str__(self):
return f"type[ {tp} ]{input_type}{path}{input_value}\n{errors}"
except Exception as e:
return f"cwtch internal error: {e}\noriginal errors: {self.errors}"

def __repr__(self):
return f"{self.__class__.__name__} {self}"
Loading

0 comments on commit 2695e11

Please sign in to comment.