Skip to content

Fix/console.print failed to render weakref.proxy objects #3684

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

Open
wants to merge 4 commits into
base: master
Choose a base branch
from

Conversation

shyam-ramani
Copy link

fixes #3656

Title: Improve Rich's Pretty Inspection to Handle Weakref Proxies Gracefully

Description:
This PR enhances Rich's inspection system by adding explicit handling for weakref.proxy objects in the safe_repr function. It prevents ReferenceError exceptions when inspecting dead weakref proxies and ensures consistent output formatting.

Key Changes:

  • Added explicit handling for weakref proxy types in safe_repr.
  • Checks proxy validity using object.__getattribute__(obj, "__callback__"), avoiding accidental forwarding.
  • Returns <weakproxy ...; dead> when the reference is broken.
  • Updates the Pretty class to use the modified safe_repr function.
  • Maintains compatibility with existing weakref.ref handling.

Benefits:

✅ Prevents ReferenceError when inspecting dead weakref proxies.
✅ Matches Python's native weakref.ref behavior.
✅ Provides detailed output for alive proxies while marking dead ones explicitly.
✅ Ensures better debugging experience when dealing with weak references.

Verification:

import weakref
from rich import print

class TempClass:
    def __repr__(self):
        return "<TempClass>"

obj = TempClass()
proxy_obj = weakref.proxy(obj)

# Alive proxy
print(proxy_obj)  # Outputs: <weakproxy at 0x... to TempClass at 0x...>

# Dead proxy
del obj
print(proxy_obj)  # Now outputs: <weakproxy at 0x...; dead>

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] console.print failed to render weakref.proxy objects
1 participant