Method to know if object support being weakreferenced ?

Matthias Bussonnier bussonniermatthias at gmail.com
Mon Dec 12 23:57:34 EST 2016


Hi all, 

I was recently had to use weakreferences, using the weakref module, and came across the fact that some object cannot be weakreferenced. If you try to do so you get greated by a TypeError, which is a totally expected and documented behavior. 

As I tend to prefer the "Look before you leap" approach I search for a method capable of telling me whether an object can be weakreferenced. Which I failed to found. 

I could of course write a function that try/except and return False/True depending on the result, but that seem suboptimal as how can I know that the TypeError does come from not being able to take a weak reference ? And not from something else ?

The common Idiom in CPython, at the C layer seem to be PyType_SUPPORTS_WEAKREFS(Py_TYPE(ob)). So I can (and did) write a C-extension that expose such a function, but it does seem silly that no one else did that before me, and that no one seemed to have encountered the problem before. 

So am I missing something ? Is such a function not useful ?  Is there any reason not to have it in the stdlib ?

Thanks.
-- 
M


More information about the Python-list mailing list