cours/python références faibles.md
Oscar Plaisant 602a41e7f8 update
2024-12-25 22:30:24 +01:00

35 lines
1.3 KiB
Markdown
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

source:: [[Variables, scopes et closures en Python - Bibliothèque - Zeste de Savoir]]
#s/informatique/langage/python
Une solution possible pour libérer la mémoire malgré les [[python références cycliques|références cycliques]].
Le problème des références cycliques provient du fait que le ramasse-miettes ne peut collecter les objets tant quils sont référencés. Une autre manière de le résoudre est alors dutiliser des références qui nempêchent pas ce ramasse-miettes de supprimer les valeurs. On les appelle «références faibles» et elles sont fournies en Python par le module [weakref](https://docs.python.org/3/library/weakref.html).
Une référence faible est similaire à un appel de fonction qui renvoie lobjet si celui-ci est toujours référencé, ou `None` sil a été supprimé.
```python
>>> import weakref
>>>
>>> class Obj:
... def __del__(self):
... print('deleting', self)
...
>>>
>>> obj1 = Obj()
>>> obj2 = Obj()
>>> obj1.ref = obj2
>>> obj2.ref = weakref.ref(obj1)
>>>
>>> obj2.ref
<weakref at 0x7f8de5d69408; to 'Obj' at 0x7f8de5d6b128>
>>> print(obj2.ref())
<__main__.Obj object at 0x7f8de5d6b128>
>>> obj2.ref() is obj1
True
>>>
>>> del obj1
deleting <__main__.Obj object at 0x7f8de5d6b128>
>>> print(obj2.ref())
None
```