Skip to content

Commit e77cdf2

Browse files
committed
Fix handling of non-class & non-string annotations in dataclass
Fix: #86
1 parent 5fb12dc commit e77cdf2

File tree

3 files changed

+49
-1
lines changed

3 files changed

+49
-1
lines changed

logwrap/repr_utils.py

+6-1
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
import types
2828
from inspect import Parameter
2929
from inspect import Signature
30+
from inspect import isclass
3031
from inspect import signature
3132
from typing import TYPE_CHECKING
3233
from typing import Any
@@ -469,8 +470,12 @@ def _repr_dataclass(
469470
if field.type:
470471
if isinstance(field.type, str):
471472
comment.append(f"type: {field.type}")
472-
else:
473+
elif isinstance(field.type, ForwardRef):
474+
comment.append(f"type: {field.type!r}")
475+
elif isclass(field.type):
473476
comment.append(f"type: {field.type.__name__}")
477+
else:
478+
comment.append(f"type: {field.type!r}")
474479
if getattr(field, "kw_only", False): # python 3.10+
475480
comment.append("kw_only")
476481

test/test_log_wrap.py

+30
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,9 @@
1818

1919
"""Python independent logwrap tests."""
2020

21+
from __future__ import annotations
22+
23+
import dataclasses
2124
import functools
2225
import io
2326
import logging
@@ -612,6 +615,33 @@ def func():
612615
)
613616
# fmt: on
614617

618+
def test_025_union_ann_call_arg(self):
619+
@dataclasses.dataclass
620+
class WithUnionAnn:
621+
a: int | None
622+
623+
@logwrap.logwrap
624+
def func(val: WithUnionAnn) -> WithUnionAnn:
625+
return val
626+
627+
func(WithUnionAnn(1))
628+
# fmt: off
629+
self.assertEqual(
630+
"DEBUG>Calling: \n"
631+
"func(\n"
632+
" # POSITIONAL_OR_KEYWORD:\n"
633+
" val=test_log_wrap.WithUnionAnn(\n"
634+
" a=1, # type: int | None\n"
635+
" ), # type: WithUnionAnn\n"
636+
")\n"
637+
"DEBUG>Done: 'func' with result:\n"
638+
"test_log_wrap.WithUnionAnn(\n"
639+
" a=1, # type: int | None\n"
640+
")\n",
641+
self.stream.getvalue(),
642+
)
643+
# fmt: on
644+
615645

616646
# noinspection PyMissingOrEmptyDocstring
617647
class TestObject(unittest.TestCase):

test/test_repr_utils.py

+13
Original file line numberDiff line numberDiff line change
@@ -334,6 +334,19 @@ def test_005_deque(self):
334334
logwrap.pretty_repr(default_deque),
335335
)
336336

337+
def tests_006_union_ann(self):
338+
@dataclasses.dataclass
339+
class WithUnionAnn:
340+
a: int | None
341+
342+
test_dc = WithUnionAnn(None)
343+
self.assertEqual(
344+
"test_repr_utils.WithUnionAnn(\n"
345+
" a=None, # type: int | None\n"
346+
")",
347+
logwrap.pretty_repr(test_dc),
348+
)
349+
337350

338351
class TestRich(unittest.TestCase):
339352
class Bird:

0 commit comments

Comments
 (0)