Skip to content

Commit

Permalink
Merge pull request #2379 from saulshanabrook/tuple-rich-repr-positional
Browse files Browse the repository at this point in the history
Fix using tuples as positional arguments in rich repr
  • Loading branch information
willmcgugan committed Sep 19, 2022
2 parents eaba862 + f0cbc46 commit 6a81094
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 0 deletions.
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()"

0 comments on commit 6a81094

Please sign in to comment.