Skip to content

Commit

Permalink
Merge pull request #43 from erezsh/dev
Browse files Browse the repository at this point in the history
Deprecate iter(dataclass_instance), which was a confusing behavior.
  • Loading branch information
erezsh authored Sep 29, 2023
2 parents 68917e8 + f18cc46 commit 6b92678
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 4 deletions.
11 changes: 9 additions & 2 deletions runtype/dataclass.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from abc import ABC, abstractmethod
import inspect
import types
import warnings

if TYPE_CHECKING:
from typing_extensions import dataclass_transform
Expand Down Expand Up @@ -201,14 +202,19 @@ def replace(inst, **kwargs):

def __iter__(inst):
"Yields a list of tuples [(name, value), ...]"
# TODO: deprecate this method
warnings.warn("This method is deprecated and will be removed in future versions."
"Please use `.asdict()` or `.asitems()` instead.", DeprecationWarning)
return ((name, getattr(inst, name)) for name in inst.__dataclass_fields__)

def asdict(inst):
"""Returns a dict of {name: value, ...}
"""
return {name: getattr(inst, name) for name in inst.__dataclass_fields__}

def asitems(inst):
"Yields a list of tuples [(name, value), ...]"
return ((name, getattr(inst, name)) for name in inst.__dataclass_fields__)

def aslist(inst):
"""Returns a list of the values
"""
Expand All @@ -234,7 +240,7 @@ def json(inst):
"""Returns a JSON of values, going recursively into other objects (if possible)"""
return {
k: _json_rec(v)
for k, v in inst
for k, v in inst.asitems()
}

def _set_if_not_exists(cls, d):
Expand Down Expand Up @@ -317,6 +323,7 @@ def __post_init__(self):
_set_if_not_exists(c, {
'replace': replace,
'asdict': asdict,
'asitems': asitems,
'aslist': aslist,
'astuple': astuple,
'json': json,
Expand Down
4 changes: 2 additions & 2 deletions tests/test_basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -659,10 +659,10 @@ def __post_init__(self):
assert self.x != 0

p = Point(2,3)
assert dict(p) == {'x':2, 'y':3}
assert p.asdict() == {'x':2, 'y':3}

p2 = p.replace(x=30)
assert dict(p2) == {'x':30, 'y':3}
# assert dict(p2) == {'x':30, 'y':3}
assert p2.aslist() == [30, 3]
assert p2.astuple() == (30, 3)

Expand Down

0 comments on commit 6b92678

Please sign in to comment.