f



Method to know if object support being weakreferenced ?

Hi all,=20

I was recently had to use weakreferences, using the weakref module, and cam=
e 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 docum=
ented behavior.=20

As I tend to prefer the "Look before you leap" approach I search for a meth=
od capable of telling me whether an object can be weakreferenced. Which I f=
ailed to found.=20

I could of course write a function that try/except and return False/True de=
pending 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_WEAK=
REFS(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.=20

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

Thanks.
--=20
M
0
Matthias
12/13/2016 4:57:34 AM
comp.lang.python 77058 articles. 6 followers. Post Follow

2 Replies
571 Views

Similar Articles

[PageSpeed] 20

On Tuesday 13 December 2016 15:57, Matthias Bussonnier wrote:

[...]
> 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 ?

Do you mean something like this?

try:
    proxy = weakref.proxy(obj)
except TypeError:
    proxy = None


Where else could it come from?

> 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 ?

You could try raising a feature request on the bug tracker.



-- 
Steven
"Ever since I learned about confirmation bias, I've been seeing 
it everywhere." - Jon Ronson

0
Steven
12/13/2016 6:00:02 AM
Matthias Bussonnier wrote:
> I search for a method
> capable of telling me whether an object can be weakreferenced.

Objects that can be weakly referenced have a __weakref__ attribute.
So you could use hasattr(obj, '__weakref__').

-- 
Greg
0
Gregory
12/13/2016 6:21:45 AM
Reply: