RFC: Proposal: Deterministic Object Destruction

Chris Angelico rosuav at gmail.com
Mon Mar 5 12:58:20 EST 2018


On Tue, Mar 6, 2018 at 4:53 AM, Ooomzay <ooomzay at gmail.com> 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?
If so, you can trivially add another level to the nesting.

ChrisA



More information about the Python-list mailing list