-
Notifications
You must be signed in to change notification settings - Fork 1
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
Add PyWeakref_IsDead()
to test if a weak reference is dead
#48
Comments
Your rationale makes sense so adding I would just add an error case: raise an exception (TypeError) and return -1 if the argument is not a weak reference object. |
An alternative is allowing Unfortunately, allowing the |
I've updated the issue to specify a |
On one hand, |
@serhiy-storchaka - you need it any time you want to implement a collection of weakrefs (things like It's not just a matter of efficiency. As I wrote in the issue:
|
On third hand, what is dead will remain dead forever. For the purpose of weakref collections this should be enough. I support this proposition. |
I added a vote in the first message: please vote :-) |
Can we guarantee that it does not fail if the argument is a weakref? |
I think that it's a reasonable assumption, yes. |
EDIT: Added,
-1
error return case per @vstinner's suggestion.EDIT 2: @vstinner added a vote.
I propose adding a dedicated C API function to check if a weak reference is dead:
Motivation
Prior to Python 3.13, you could check if a weak reference is dead via
PyWeakref_GetObject(ref) == Py_None
, but that function is now deprecated. You might try writing an "is dead" check usingPyWeakref_GetRef
. For example:In addition to not being ergonomic, the problem with this code is that the
Py_DECREF(tmp)
may introduce a side effect from a calling a destructor, at least in the free threading build where some other thread may concurrently drop the last reference. Our internal_PyWeakref_IS_DEAD
implementation avoids this problem, but it's not possible to reimplement that code using our existing public APIs.This can be a problem when you need to check if a weak reference is dead within a lock, such as when cleaning up dictionaries or lists of weak references -- you don't want to execute arbitrary code via a destructor while holding the lock.
I've run into this in two C API extensions this week that are not currently thread-safe with free threading:
PyWeakReference
, but the "is dead" clean-up checks are more difficult due to the above issues.Vote
The text was updated successfully, but these errors were encountered: