[New-bugs-announce] [issue45555] Object stays alive for weak reference if an exception happens in constructor

Matias G report at bugs.python.org
Thu Oct 21 10:54:42 EDT 2021


New submission from Matias G <guijarro at esrf.fr>:

Hi Python developers,

I stumbled on a weird behavior, which might be a bug actually.

I am surprised by the output of the following piece of code:

```
import weakref

refs = []

class A:
    def __init__(self):
        refs.append(weakref.ref(self))
        #raise RuntimeError() <<< enable this line of code and be surprised!

try:
    A()
finally:
    print(refs[0]())
```

The code prints None ; but, if the RuntimeError exception is raised
in the constructor, we find the object in the final print. It is not
dereferenced properly, as it seems:

```
<__main__.A object at 0x7f4b6cf23ed0>
Traceback (most recent call last):
  File "/tmp/test.py", line 11, in <module>
    A()
  File "/tmp/test.py", line 8, in __init__
    raise RuntimeError()
RuntimeError
```

I tried adding `gc.collect()` with no luck.

Am I doing something wrong ?

Thanks in advance

----------
components: Interpreter Core
messages: 404606
nosy: guijarro
priority: normal
severity: normal
status: open
title: Object stays alive for weak reference if an exception happens in constructor
type: behavior
versions: Python 3.7

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue45555>
_______________________________________


More information about the New-bugs-announce mailing list