Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion rich/_inspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,12 @@ def safe_getattr(attr_name: str) -> Tuple[Any, Any]:
return (error, None)

obj = self.obj
keys = dir(obj)
if not self.sort and hasattr(obj, "__dict__"):
# Preserve instance attribute insertion order
keys = list(obj.__dict__.keys())
else:
keys = dir(obj)

total_items = len(keys)
if not self.dunder:
keys = [key for key in keys if not key.startswith("__")]
Expand Down
21 changes: 21 additions & 0 deletions tests/test_inspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -497,7 +497,28 @@ def test_object_types_mro_as_strings(obj: object, expected_result: Sequence[str]
# fmt: on
),
)

def test_object_is_one_of_types(
obj: object, types: Sequence[str], expected_result: bool
):
assert is_object_one_of_types(obj, types) is expected_result

def test_inspect_preserves_instance_attribute_order_when_sort_false():
class Example:
def __init__(self):
self.b = 1
self.a = 2

example = Example()

# Render inspect output with sort=False
output = render(example, methods=False, value=False, sort=False)

# Attribute order should be preserved: b then a
b_index = output.find("b = 1")
a_index = output.find("a = 2")

assert b_index != -1
assert a_index != -1
assert b_index < a_index