[issue28278] Make `weakref.WeakKeyDictionary.__repr__` meaningful

Josh Rosenberg report at bugs.python.org
Mon Sep 26 13:58:34 EDT 2016


Josh Rosenberg added the comment:

Well, I could see a "friendly" repr being avoided to:

1. Save work (iterating safely involves iteration guards and explicitly acquiring strong references to every key)
2. Avoid pretending the state is stable (the repr at time X could be different at time X+epsilon)
3. Avoiding the possibility of __repr__ implementations for contained items doing terrible things (e.g. mutating the WeakKeyDictionary, or deleting the last external reference to a key). In the case where a __repr__ deletes the last external reference to a key that WeakKeyDictionary's __repr__ already iterated past, it means the repr is wrong before it even returns.
4. The repr wouldn't match the normal repr behavior; ideally, you can copy and paste a repr and get back an equivalent object. But of course, copy and pasting WeakKeyDictionary({Spam(1): 1, Spam(2): 2}) would actually get you back WeakKeyDictionary({}), because the objects you passed in don't share the identity of the ones in the original WeakKeyDictionary (which have existing references somewhere), and the instant the constructor returns, they'd lose their last reference and be deleted from the newly created WeakKeyDictionary
5. The above problems get even worse if the repr ends up being reentrant (which is more likely in this case; weakrefs are often used to break cycles); any stage of the recursive repr could end up mutating

None of these mean that the feature would be impossible/undesirable. #4 *might* be a reason to keep __repr__ as is though, and have __str__ display the more friendly version (e.g. `return '{}({!r})'.format(type(self).__name__, dict(self))` ); __str__ is supposed to be friendly without being a means of reproducing the object, so it wouldn't be quite as misleading.

----------
nosy: +josh.r

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue28278>
_______________________________________


More information about the Python-bugs-list mailing list