Proposal:

Have a weakref.link (not at all attached to the naming) primitive that allows 
one to keep object A alive while object B is alive. This would be functionally 
similar to adding A as an attribute of B from the GC's perspective without 
making any assumptions about what attributes are available in B. Here's a 
really course example of how this might be used:

# Associate "extra_data" with "obj" where "extra_data" will lose its reference 
when "obj" is no longer reachable through strong refs.
my_link = weakref.link(obj, extra_data)

...

obj, extra_data = my_link()
if obj is not None:
  do_something(obj, extra_data)


This would also allow us to fix or create a new version of WeakKeyDictionary 
where values can have strong references back to their key without preventing 
their key from being reclaimed. This has been an issue for tensorflow in the 
past (see https://github.com/tensorflow/tensorflow/issues/42022) and is likely 
to be a subtle issue in many more libraries. Even the suggested use case in the 
docs "This can be especially useful with objects that override attribute 
accesses." is likely to be broken because of this issue.  While I'd be weary of 
changing the semantics of an existing data structure it seems highly unlikely 
anything depends on this behavior since it makes WeakKeyDictionary degrade to 
behaving like a normal dictionary for that key.


Notes:
* Not attached to this specific approach or API
* Mostly interesting in updating/creating new WeakKeyDictionary as mentioned
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/4KBLRV7QYS36NVJNKAJIDCFTH4DF5YSY/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to