RFC: Proposal: Deterministic Object Destruction

Ooomzay ooomzay at gmail.com
Mon Mar 5 15:01:21 EST 2018


On Monday, 5 March 2018 17:58:40 UTC, Chris Angelico  wrote:
> On Tue, Mar 6, 2018 at 4:53 AM, Ooomzay wrote:
> > 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.
> 
> What is B? Is it something that's notionally a resource to be managed?

Yes. For example a supply of electrical power controlled via a serial protocol  to a programmable power supply - the file is a private detail used for the communications. And lets imagine that this powersupply object needs to keep track of some state such as the voltage - and it has a long lifetime - not just created then destroyed in scope of one function i.e. it is a substantial object.

> If so, you can trivially add another level to the nesting.

Please illustrate. I really do want to be able to compare like for like.



More information about the Python-list mailing list