Also, check out https://docs.python.org/3/library/weakref.html <https://docs.python.org/3/library/weakref.html>
Maybe it will not provide exactly what you indicated, but might get some ideas how to do things differently. — Now is better than never. Although never is often better than *right* now. == Deferred Evaluation — Dg > On 9 Sep 2023, at 09:02, Jeff Allen <ja...@farowl.co.uk> wrote: > > On 06/09/2023 03:47, Daniel Walker wrote: >> Perhaps this is a solution in search of a problem but I recently encountered >> this situation in one of my projects. >> >> I have an object, foo, which, due to the references it contains, I'd rather >> not keep around longer than necessary. >> >> I use foo to instantiate another object: >> >> bar = Bar(foo) >> >> bar is free to manipulate foo however it wants and even del it if necessary. >> However, since the foo name is still around, those resources won't get >> cleaned up even if bar is done with them. The simple solution is >> > It's a neat idea but there are other ways that may be better. > > I assume foo is a "specification", that is, an object you configure through a > number of optional calls or attribute assignments, then pass to Bar() as a > design alternative to Bar() having a complicated set of arguments. A pattern > often used is the fluent API: > > bar = Bar(Foo().a().b(42).c('penguin')) > > Now only Bar has a reference to the Foo you made. > > But foo is not necessarily destroyed immediately the last reference to it is > dropped, even with del or when nameless in the fluent API. If you wanted to > be certain, you could make Foo a context manager to use like this: > > with Foo() as foo: > foo.a() > foo.b(42) > foo.c('penguin') > bar = Bar(foo) > bar.do_stuff() > (Think I got that right. Not tried it.) Now Foo.__exit__ can be made to > properly tear down the resources in a foo. > > -- > > Jeff Allen > _______________________________________________ > Python-ideas mailing list -- python-ideas@python.org > To unsubscribe send an email to python-ideas-le...@python.org > https://mail.python.org/mailman3/lists/python-ideas.python.org/ > Message archived at > https://mail.python.org/archives/list/python-ideas@python.org/message/75EXWHY3SFZSZTZUQJPIBMXFRF3J327I/ > Code of Conduct: http://python.org/psf/codeofconduct/
_______________________________________________ Python-ideas mailing list -- python-ideas@python.org To unsubscribe send an email to python-ideas-le...@python.org https://mail.python.org/mailman3/lists/python-ideas.python.org/ Message archived at https://mail.python.org/archives/list/python-ideas@python.org/message/ICXLYHODLH3RVUQCJAHFZA56RBQTG7YI/ Code of Conduct: http://python.org/psf/codeofconduct/