Skip to content

Commit 6b92678

Browse files
authored
Merge pull request #43 from erezsh/dev
Deprecate iter(dataclass_instance), which was a confusing behavior.
2 parents 68917e8 + f18cc46 commit 6b92678

File tree

2 files changed

+11
-4
lines changed

2 files changed

+11
-4
lines changed

runtype/dataclass.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
from abc import ABC, abstractmethod
1111
import inspect
1212
import types
13+
import warnings
1314

1415
if TYPE_CHECKING:
1516
from typing_extensions import dataclass_transform
@@ -201,14 +202,19 @@ def replace(inst, **kwargs):
201202

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

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

214+
def asitems(inst):
215+
"Yields a list of tuples [(name, value), ...]"
216+
return ((name, getattr(inst, name)) for name in inst.__dataclass_fields__)
217+
212218
def aslist(inst):
213219
"""Returns a list of the values
214220
"""
@@ -234,7 +240,7 @@ def json(inst):
234240
"""Returns a JSON of values, going recursively into other objects (if possible)"""
235241
return {
236242
k: _json_rec(v)
237-
for k, v in inst
243+
for k, v in inst.asitems()
238244
}
239245

240246
def _set_if_not_exists(cls, d):
@@ -317,6 +323,7 @@ def __post_init__(self):
317323
_set_if_not_exists(c, {
318324
'replace': replace,
319325
'asdict': asdict,
326+
'asitems': asitems,
320327
'aslist': aslist,
321328
'astuple': astuple,
322329
'json': json,

tests/test_basic.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -659,10 +659,10 @@ def __post_init__(self):
659659
assert self.x != 0
660660

661661
p = Point(2,3)
662-
assert dict(p) == {'x':2, 'y':3}
662+
assert p.asdict() == {'x':2, 'y':3}
663663

664664
p2 = p.replace(x=30)
665-
assert dict(p2) == {'x':30, 'y':3}
665+
# assert dict(p2) == {'x':30, 'y':3}
666666
assert p2.aslist() == [30, 3]
667667
assert p2.astuple() == (30, 3)
668668

0 commit comments

Comments
 (0)