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

Deprecate iter(dataclass_instance), which was a confusing behavior. #43

Merged
merged 1 commit into from
Sep 29, 2023
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
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), ...]"
erezsh marked this conversation as resolved.
Show resolved Hide resolved
# 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
Loading