Skip to content

Commit 00047cb

Browse files
authored
support dataclasses with slots (#136)
1 parent c17c310 commit 00047cb

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

devtools/prettier.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -254,7 +254,12 @@ def _format_ast_expression(self, value: ast.AST, _: str, indent_current: int, in
254254
self._stream.write(indent_current * self._c + line)
255255

256256
def _format_dataclass(self, value: 'Any', _: str, indent_current: int, indent_new: int) -> None:
257-
self._format_fields(value, value.__dict__.items(), indent_current, indent_new)
257+
try:
258+
field_items = value.__dict__.items()
259+
except AttributeError:
260+
# slots
261+
field_items = ((f, getattr(value, f)) for f in value.__slots__)
262+
self._format_fields(value, field_items, indent_current, indent_new)
258263

259264
def _format_sqlalchemy_class(self, value: 'Any', _: str, indent_current: int, indent_new: int) -> None:
260265
if sa_inspect is not None:

tests/test_prettier.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -255,6 +255,30 @@ class BarDataclass:
255255
)
256256

257257

258+
def test_dataclass_slots():
259+
try:
260+
dec = dataclass(slots=True)
261+
except TypeError:
262+
pytest.skip('dataclasses.slots not available')
263+
264+
@dec
265+
class FooDataclass:
266+
x: int
267+
y: str
268+
269+
f = FooDataclass(123, 'bar')
270+
v = pformat(f)
271+
print(v)
272+
assert (
273+
v
274+
== """\
275+
FooDataclass(
276+
x=123,
277+
y='bar',
278+
)"""
279+
)
280+
281+
258282
@pytest.mark.skipif(numpy is None, reason='numpy not installed')
259283
def test_indent_numpy():
260284
v = pformat({'numpy test': numpy.array(range(20))})

0 commit comments

Comments
 (0)