[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

RFC: Proposal: Deterministic Object Destruction

On Sunday, 4 March 2018 23:56:09 UTC, Chris Angelico  wrote:
> On Sun, Mar 4, 2018 at 10:37 PM, Ooomzay  wrote:
> > Please consider the case of a composite resource: You need to implement
> > __enter__, __exit__ and track the open/closed state at every level in
> > your component hierarchy - even if some levels hold no resources directly.
> >
> > This is burdensome, breaks encapsulation, breaks invariance and is error prone
> > ...very unpythonic.
> Why do you need to? I don't understand your complaint here - can you
> give an example of a composite resource that needs this kind of
> special management?

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() 

Under this PEP this is all that is needed to guarantee that the files "a" 
and "b" are closed on exit from main or after any exception has been handled. 

Also note that if you have a reference to these objects then they are 
guaranteed to be in a valid/useable/open state (invariant) - no danger 
or need to worry/check about enter/exit state. 

Now repeat this exercise with "with".