RFC: Proposal: Deterministic Object Destruction

Ooomzay ooomzay at gmail.com
Mon Mar 5 12:22:33 EST 2018


On Monday, 5 March 2018 16:47:02 UTC, Steven D'Aprano  wrote:
> On Sun, 04 Mar 2018 16:58:38 -0800, Ooomzay wrote:
> 
> > Here is an example of a composite resource using RAII:-
> > 
> > class RAIIFileAccess():
> >     def __init__(self, fname):
> >         print("%s Opened" % fname)
> >     def __del__(self):
> >         print("%s Closed" % fname)
> > 
> > class A():
> >     def __init__(self):
> >         self.res = RAIIFileAccess("a")
> > 
> > class B():
> >     def __init__(self):
> >         self.res = RAIIFileAccess("b")
> > 
> > class C():
> >     def __init__(self):
> >         self.a = A()
> >         self.b = B()
> >                  
> > def main():
> >     c = C()
> 
> Looking at that code, my major thought is  that there is far too much OO 
> design, not enough simplicity.

If this is far too much OO for you then RAII will be of no 
interest to you.

This example was specifically in response to a request to
illustrate the relative simplicity of RAII in the case of a 
composite (OO) resource.

> Perhaps I'm missing something, but I have no idea what benefit there is 
> in that style of code over:
> 
> with open('a') as a:
>     with open('b') as b:
>         process(a, b)

Encapsulation. Your application code is now managing details 
that should be hidden in the object. This PEP and RAII are
unashamedly targeted at OO designs.

If you would like to have a shot at coding this without RAII,
but preserving the OO design, you will find that it is 
considerably _simpler_ than the with/context manager approach.

> So long as you only process a or b inside the nested block, you are 
> guaranteed that they will be open.
> 
> And unlike your RAII example, they will be closed when you exit, 
> regardless of how many references to them you have, regardless of whether 
> an exception occurs or not, regardless of whether there are cycles or 
> whether they are globals or whether the interpreter is shutting down.

If you choose RAII you will not be cavalier with your references.

> I think that at this point, you have convinced me that you want to impose 
> enormous costs on all Python interpreters *and* Python developers, in 
> order to allow you to write C++ code in Python rather than learn Pythonic 
> idioms like the with statement.

On interpreters yes. On developers no. You can carry on exactly as you are.



More information about the Python-list mailing list