Skip to content

Commit

Permalink
Merge pull request #4142 from HypothesisWorks/DRMacIver/qualname-in-p…
Browse files Browse the repository at this point in the history
…retty

Include namespace classes in pretty printing
  • Loading branch information
Zac-HD authored Oct 23, 2024
2 parents ef9942d + 479ca98 commit 8f93105
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 3 deletions.
3 changes: 3 additions & 0 deletions hypothesis-python/RELEASE.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
RELEASE_TYPE: patch

This release improves pretty printing of nested classes to include the outer class name in their printed representation.
10 changes: 7 additions & 3 deletions hypothesis-python/src/hypothesis/vendor/pretty.py
Original file line number Diff line number Diff line change
Expand Up @@ -582,6 +582,10 @@ def inner(obj, p, cycle):
return inner


def get_class_name(cls):
return _safe_getattr(cls, "__qualname__", cls.__name__)


def _set_pprinter_factory(start, end, basetype):
"""Factory that returns a pprint function useful for sets and
frozensets."""
Expand All @@ -600,7 +604,7 @@ def inner(obj, p, cycle):
return p.text(start + "..." + end)
if not obj:
# Special case.
p.text(basetype.__name__ + "()")
p.text(get_class_name(basetype) + "()")
else:
step = len(start)
with p.group(step, start, end):
Expand Down Expand Up @@ -733,7 +737,7 @@ def _repr_pprint(obj, p, cycle):


def pprint_fields(obj, p, cycle, fields):
name = obj.__class__.__name__
name = get_class_name(obj.__class__)
if cycle:
return p.text(f"{name}(...)")
with p.group(1, name + "(", ")"):
Expand Down Expand Up @@ -879,7 +883,7 @@ def _repr_dataframe(obj, p, cycle): # pragma: no cover


def _repr_enum(obj, p, cycle):
tname = type(obj).__name__
tname = get_class_name(type(obj))
if isinstance(obj, Flag):
p.text(
" | ".join(f"{tname}.{x.name}" for x in type(obj) if x & obj == x)
Expand Down
25 changes: 25 additions & 0 deletions hypothesis-python/tests/cover/test_pretty.py
Original file line number Diff line number Diff line change
Expand Up @@ -876,3 +876,28 @@ def test_does_not_include_no_init_fields_in_attrs_printing():
assert pretty.pretty(record) == "AttrsClassWithNoInitField(x=1)"
record.y = 1
assert pretty.pretty(record) == "AttrsClassWithNoInitField(x=1)"


class Namespace:
@dataclass
class DC:
x: int

@attrs.define
class A:
x: int

class E(Enum):
A = 1


NAMESPACED_VALUES = [
Namespace.DC(x=1),
Namespace.A(x=1),
Namespace.E.A,
]


@pytest.mark.parametrize("obj", NAMESPACED_VALUES, ids=map(repr, NAMESPACED_VALUES))
def test_includes_namespace_classes_in_pretty(obj):
assert pretty.pretty(obj).startswith("Namespace.")

0 comments on commit 8f93105

Please sign in to comment.