RFC: Proposal: Deterministic Object Destruction

Ooomzay ooomzay at gmail.com
Mon Mar 5 12:53:50 EST 2018


On Monday, 5 March 2018 14:21:54 UTC, Chris Angelico  wrote:
> On Tue, Mar 6, 2018 at 12:58 AM, Ooomzay wrote:
> > Here is my fixed example, if someone else could try it in CPython and report back that would be interesting:-
> >
> > class RAIIFileAccess():
> >     def __init__(self, fname):
> >         print("%s Opened" % fname)
> >         self.fname = fname
> >
> >     def __del__(self):
> >         print("%s Closed" % self.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()
> >     c.dostuff()
> >
> > main()
> 
> Here's how I'd do it with context managers.
> 
> from contextlib import contextmanager
> 
> @contextmanager
> def file_access(fname):
>     try:
>         print("%s Opened" % fname)
>         yield
>     finally:
>         print("%s Closed" % fname)
> 
> @contextmanager
> def c():
>     try:
>         print("Starting c")
>         with file_access("a") as a, file_access("b") as b:
>             yield
>     finally:
>         print("Cleaning up c")
> 
> def main():
>     with c():
>         dostuff() # NameError
 

Thank you for having a go...

However you have broken the encapsulation of class A and B. These 
are trivial for the sake of example. I should have used
_underscores (i.e. self._res) to make the intent of
this example more obvious.

Please try again but preserving the integrity/encapsulation
of class A & B & C, just as the RAII example does.



More information about the Python-list mailing list