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

Bugfix in dataclass when frozen=False; Add docs detailing typing support #53

Merged
merged 2 commits into from
Mar 6, 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
10 changes: 8 additions & 2 deletions docs/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,22 @@ Welcome to Runtype's documentation!
===================================

.. toctree::
:maxdepth: 2
:caption: Modules
:maxdepth: 2
:hidden:

validation
dataclass
dispatch
types
benchmarks

.. toctree::
:caption: Overview
:maxdepth: 2
:hidden:

typing_support
benchmarks

Runtype is a collection of run-time type utilities for Python.

Expand Down
64 changes: 64 additions & 0 deletions docs/typing_support.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
Typing support
==============

Runtype supports a wide-range of types and typing constructs, however full-support is still work in progress.

For now, some constructs are available for validation, but not for dispatch.

Here is the detailed list:

.. list-table::
:widths: 25 25 25
:header-rows: 1

* - Types / Constructs
- Validation
- Dispatch
* - Primitives (None, bool, float, int, str, etc.)
- ✔
- ✔
* - Date primitives (datetime, date, time, timedelta)
- ✔
- ✔
* - Containers, non-generic (list, tuple, dict)
- ✔
- ✔
* - Callable, non-generic (callable)
- ✔
- ✔
* - abc.Set, abc.MutableMapping, etc.
- ✔
- ✔
* - typing.AbstractSet
- ✔
- ✔
* - typing.Any
- ✔
- ✔
* - typing.Union, Optional
- ✔
- ✔
* - typing.Type (Type[x])
- ✔
- ✔
* - typing.Literal
- ✔
- ✔
* - Generic containers (list[x], tuple[x], dict[x])
- ✔
- TODO
* - Infinite tuple (tuple[x, ...])
- ✔
- TODO
* - Generic callable
- TODO
- TODO
* - typing.IO
- TODO
- TODO
* - TypeVar
- TODO
- TODO
* - Protocol
- TODO
- TODO
8 changes: 5 additions & 3 deletions runtype/dataclass.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ def dataclass_transform(*a, **kw):
from .pytypes import TypeCaster, SumType, NoneType, ATypeCaster, PythonType, type_caster

Required = object()
Skip = object()
MAX_SAMPLE_SIZE = 16

class NopTypeCaster(ATypeCaster):
Expand Down Expand Up @@ -150,6 +151,7 @@ def _validate_attr(config, should_cast, sampler, obj, name, type_, value):
if item_value is not value:
msg += f'\n\n Failed on item: {item_value!r}, expected type {item_type}'
raise TypeError(msg)
return Skip

def _post_init(self, config, should_cast, sampler, type_caster):
for name, field in getattr(self, '__dataclass_fields__', {}).items():
Expand All @@ -160,7 +162,7 @@ def _post_init(self, config, should_cast, sampler, type_caster):

type_ = _get_field_type(type_caster, field)
new_value = _validate_attr(config, should_cast, sampler, self, name, type_, value)
if new_value is not None:
if new_value is not Skip:
object.__setattr__(self, name, new_value)

def _post_init__no_check_types(self):
Expand All @@ -174,11 +176,11 @@ def _setattr(obj, setattr, name, value, config, should_cast, sampler, type_caste
try:
field = obj.__dataclass_fields__[name]
except (KeyError, AttributeError):
new_value = None
new_value = Skip
else:
type_ = _get_field_type(type_caster, field)
new_value = _validate_attr(config, should_cast, sampler, obj, name, type_, value)
setattr(obj, name, value if new_value is None else new_value)
setattr(obj, name, value if new_value is Skip else new_value)


def replace(inst, **kwargs):
Expand Down
10 changes: 10 additions & 0 deletions tests/test_basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -890,6 +890,16 @@ class A:
else:
assert False

def test_unfrozen2(self):
@dataclass(frozen=False)
class A:
a: list = None

a = A([1,2])
assert a.a == [1,2]
a.a = None
assert a.a is None

def test_frozen(self):
@dataclass
class A:
Expand Down
21 changes: 21 additions & 0 deletions tests/test_casts.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,3 +159,24 @@ class Person:
bla: int = None

assert Person("Albert Einstein") == Person(('Albert', 'Einstein'), None) == Person(['Albert', 'Einstein'])

def test_cast_in_unfrozen(self):
@dataclass
class CastToNone:
@classmethod
def cast_from(cls, c: str):
if c == 'none':
return None
return c

@dataclass(check_types='cast', frozen=False)
class A:
s: CastToNone

assert A('hello').s == 'hello'
assert A('none').s is None
a = A('hello')
a.s = 'bla'
assert a.s == 'bla'
a.s = None
assert a.s is None
Loading