Skip to content

Conversation

@Nabeelshar
Copy link

Type of changes

  • Bug fix
  • New feature
  • Documentation / docstrings
  • Tests
  • Other

AI?

  • AI was used to generate this PR

Checklist

  • I've run the latest black with default args on new code.
  • I've updated CHANGELOG.md and CONTRIBUTORS.md where appropriate.
  • I've added tests for new code.
  • I accept that @willmcgugan may be pedantic in the code review.

Description

Fixed issue #3432 where inspect() was not respecting the sort=False parameter for instance attributes.

Problem

When calling rich.inspect(obj, sort=False), the attributes were still displayed in alphabetically sorted order instead of preserving their insertion order.

Root Cause

The _render() method was using dir() to get the list of attributes. Since Python's dir() always returns attributes in sorted order, even when sort=False was specified, the attributes were already sorted before the sorting logic was applied.

Solution

Modified the _render() method in rich/_inspect.py to:

  1. When sort=False and the object has a __dict__, use vars(obj) to get instance attributes in their insertion order (Python 3.7+ guarantees dict insertion order)
  2. Combine instance attributes (in insertion order) with class attributes from dir()
  3. Only apply alphabetical sorting when sort=True is explicitly set

Changes

  • Modified _render() method in rich/_inspect.py
  • Added test_inspect_sort_parameter() test case
  • Updated CHANGELOG.md
  • Updated CONTRIBUTORS.md

Testing

  • All existing tests pass (42 passed, 4 skipped)
  • New test specifically validates that sort=False preserves insertion order and sort=True sorts alphabetically
  • Manual testing confirms the fix works as expected

Important: Fixes #3432

- Modified _render() in rich/_inspect.py to preserve insertion order when sort=False
- When sort=False and object has __dict__, use vars() to get instance attributes in insertion order
- Added test_inspect_sort_parameter to verify the fix
- Updated CHANGELOG.md and CONTRIBUTORS.md

Fixes Textualize#3432
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] rich.inspect() does not appear to honor the "sort" keyword argument

1 participant