From f18cc4608343abd16e24dd2f525ca7f07e9bbe83 Mon Sep 17 00:00:00 2001 From: Erez Shinan Date: Fri, 29 Sep 2023 16:31:27 +0300 Subject: [PATCH] Deprecate iter(dataclass_instance), which was a confusing behavior. --- runtype/dataclass.py | 11 +++++++++-- tests/test_basic.py | 4 ++-- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/runtype/dataclass.py b/runtype/dataclass.py index 645b4b6..f236a35 100644 --- a/runtype/dataclass.py +++ b/runtype/dataclass.py @@ -10,6 +10,7 @@ from abc import ABC, abstractmethod import inspect import types +import warnings if TYPE_CHECKING: from typing_extensions import dataclass_transform @@ -201,7 +202,8 @@ 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): @@ -209,6 +211,10 @@ def asdict(inst): """ 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 """ @@ -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): @@ -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, diff --git a/tests/test_basic.py b/tests/test_basic.py index 53c8eac..06222c2 100644 --- a/tests/test_basic.py +++ b/tests/test_basic.py @@ -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)