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

Fix using tuples as positional arguments in rich repr #2379

Merged
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -13,6 +13,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Parse ANSI escape sequences in pretty repr https://github.com/Textualize/rich/pull/2470
- Add support for `FORCE_COLOR` env var https://github.com/Textualize/rich/pull/2449
- Allow a `max_depth` argument to be passed to the `install()` hook https://github.com/Textualize/rich/issues/2486
- Document using `None` as name in `__rich_repr__` for tuple posotional args https://github.com/Textualize/rich/pull/2379

### Fixed

Expand Down
2 changes: 2 additions & 0 deletions docs/source/pretty.rst
Expand Up @@ -157,6 +157,8 @@ Each tuple specifies an element in the output.
- ``yield name, value`` will generate a keyword argument.
- ``yield name, value, default`` will generate a keyword argument *if* ``value`` is not equal to ``default``.

If you use ``None`` as the ``name``, then it will be treated as a positional argument as well, in order to support having ``tuple`` positional arguments.

You can also tell Rich to generate the *angular bracket* style of repr, which tend to be used where there is no easy way to recreate the object's constructor. To do this set the function attribute ``"angular"`` to ``True`` immediately after your ``__rich_repr__`` method. For example::

__rich_repr__.angular = True
Expand Down
24 changes: 24 additions & 0 deletions tests/test_pretty.py
Expand Up @@ -589,3 +589,27 @@ def test_measure_pretty():

measurement = console.measure(pretty)
assert measurement == Measurement(12, 12)


def test_tuple_rich_repr():
"""
Test that can use None as key to have tuple positional values.
"""

class Foo:
def __rich_repr__(self):
yield None, (1,)

assert pretty_repr(Foo()) == "Foo((1,))"


def test_tuple_rich_repr_default():
"""
Test that can use None as key to have tuple positional values and with a default.
"""

class Foo:
def __rich_repr__(self):
yield None, (1,), (1,)

assert pretty_repr(Foo()) == "Foo()"