Skip to content

Add __callback__ property to weakref type#7590

Open
Copilot wants to merge 3 commits intomainfrom
copilot/fix-embedded-weakref-semantics
Open

Add __callback__ property to weakref type#7590
Copilot wants to merge 3 commits intomainfrom
copilot/fix-embedded-weakref-semantics

Conversation

Copy link
Copy Markdown
Contributor

Copilot AI commented Apr 13, 2026

RustPython's weakref type was missing the __callback__ read-only property, blocking PyO3 weakref compatibility (e.g. reference.getattr("__callback__") fails).

Changes

  • crates/vm/src/object/core.rs: Add get_callback() to PyWeak — reads the callback field under the stripe lock using the same double-check pattern as upgrade()
  • crates/vm/src/builtins/weakref.rs: Expose __callback__ as a read-only #[pygetset]
  • Lib/test/test_weakref.py: Remove expectedFailure from test_callback_attribute and test_callback_attribute_after_deletion
  • extra_tests/snippets/stdlib_weakref.py: Add regression coverage
>>> import weakref
>>> class C: pass
>>> o = C()
>>> weakref.ref(o).__callback__ is None
True
>>> cb = lambda r: None
>>> weakref.ref(o, cb).__callback__ is cb
True

Semantics match CPython: returns the callback if alive, None if no callback was set or referent was collected (callback consumed during clear).

Add get_callback() method to PyWeak in core.rs that safely reads the
callback field under the stripe lock. Expose it as a read-only
__callback__ property on the weakref type, matching CPython behavior:
- Returns the callback function when one was provided and referent is alive
- Returns None when no callback was provided
- Returns None after the referent has been collected
- Raises AttributeError on assignment (read-only)

Remove @unittest.expectedFailure from test_callback_attribute and
test_callback_attribute_after_deletion in test_weakref.py.

Add regression tests to extra_tests/snippets/stdlib_weakref.py.

Agent-Logs-Url: https://github.com/RustPython/RustPython/sessions/a8689daa-4476-4645-a935-0e13c7f7bb42

Co-authored-by: youknowone <69878+youknowone@users.noreply.github.com>
Copilot AI changed the title [WIP] Fix embedded weakref semantics for PyO3 compatibility Add __callback__ property to weakref type Apr 13, 2026
Copilot AI requested a review from youknowone April 13, 2026 12:24
@github-actions
Copy link
Copy Markdown
Contributor

github-actions bot commented Apr 13, 2026

📦 Library Dependencies

The following Lib/ modules were modified. Here are their dependencies:

[x] lib: cpython/Lib/weakref.py
[x] lib: cpython/Lib/_weakrefset.py
[x] test: cpython/Lib/test/test_weakref.py (TODO: 13)
[ ] test: cpython/Lib/test/test_weakset.py

dependencies:

  • weakref

dependent tests: (205 tests)

  • weakref: test_array test_ast test_asyncio test_code test_concurrent_futures test_context test_contextlib test_copy test_ctypes test_deque test_descr test_dict test_enum test_exceptions test_file test_fileio test_frame test_functools test_gc test_generators test_genericalias test_importlib test_inspect test_io test_ipaddress test_itertools test_logging test_memoryio test_memoryview test_mmap test_ordered_dict test_pickle test_picklebuffer test_queue test_re test_scope test_set test_slice test_socket test_sqlite3 test_ssl test_struct test_sys test_tempfile test_thread test_threading test_threading_local test_type_params test_types test_typing test_unittest test_uuid test_weakref test_weakset test_xml_etree
    • asyncio: test_asyncio test_contextlib_async test_os test_sys_settrace test_unittest
    • bdb: test_bdb
    • concurrent.futures.process: test_compileall test_concurrent_futures
    • copy: test_bytes test_codecs test_collections test_copyreg test_coroutines test_csv test_decimal test_defaultdict test_dictviews test_email test_fractions test_http_cookies test_minidom test_opcache test_optparse test_platform test_plistlib test_posix test_site test_statistics test_sysconfig test_tomllib test_urllib2 test_xml_dom_minicompat test_zlib
      • argparse: test_argparse
      • collections: test_annotationlib test_bisect test_builtin test_c_locale_coercion test_call test_configparser test_contains test_ctypes test_exception_group test_fileinput test_funcattrs test_hash test_httpservers test_iter test_iterlen test_json test_math test_monitoring test_pathlib test_patma test_pprint test_pydoc test_random test_reprlib test_richcmp test_shelve test_sqlite3 test_string test_traceback test_tuple test_urllib test_userdict test_userlist test_userstring test_with
      • dataclasses: test__colorize test_ctypes test_regrtest test_zoneinfo
      • email.generator: test_email
      • gettext: test_gettext test_tools
      • http.cookiejar: test_http_cookiejar
      • http.server: test_robotparser test_urllib2_localnet test_xmlrpc
      • logging.handlers: test_pkgutil
      • mailbox: test_mailbox
      • smtplib: test_smtplib test_smtpnet
      • tarfile: test_shutil test_tarfile
      • webbrowser: test_webbrowser
    • inspect: test_abc test_asyncgen test_buffer test_grammar test_ntpath test_operator test_posixpath test_signal test_type_annotations test_yield_from test_zipimport
      • ast: test_compile test_compiler_codegen test_dis test_fstring test_future_stmt test_type_comments test_ucn test_unparse
      • cmd: test_cmd
      • importlib.metadata: test_importlib
      • pkgutil: test_runpy
      • rlcompleter: test_rlcompleter
      • trace: test_trace
    • logging: test_hashlib test_support test_urllib2net
      • hashlib: test_hmac test_unicodedata
      • multiprocessing.util: test_concurrent_futures
      • venv: test_venv
    • multiprocessing: test_fcntl test_multiprocessing_main_handling
    • symtable: test_symtable
    • tempfile: test_bz2 test_cmd_line test_ctypes test_doctest test_ensurepip test_faulthandler test_filecmp test_importlib test_launcher test_linecache test_modulefinder test_pkg test_py_compile test_selectors test_string_literals test_subprocess test_tabnanny test_termios test_threadedtempfile test_tokenize test_urllib_response test_winconsoleio test_zipapp test_zipfile test_zipfile64 test_zstd
      • ctypes.util: test_ctypes
      • urllib.request: test_sax test_urllibnet

Legend:

  • [+] path exists in CPython
  • [x] up-to-date, [ ] outdated

@youknowone
Copy link
Copy Markdown
Member

@copilot Fix CI failure

@youknowone youknowone marked this pull request as ready for review April 13, 2026 14:03
Copy link
Copy Markdown
Contributor Author

Copilot AI commented Apr 13, 2026

@copilot Fix CI failure

Fixed in 0d51428 — the lint failure was a ruff format issue with a long assert message in extra_tests/snippets/stdlib_weakref.py.

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.

Embedded _weakref semantics are incomplete for PyO3 weakref compatibility

2 participants