Equivalent to Python with Statement

Cym13 cpicard at openmailbox.org
Thu Mar 1 07:34:38 UTC 2018


On Wednesday, 28 February 2018 at 22:55:19 UTC, Seb wrote:
> On Wednesday, 28 February 2018 at 21:47:40 UTC, Cym13 wrote:
>> On Tuesday, 27 February 2018 at 16:17:20 UTC, Jonathan wrote:
>>> I know Python's `with` statement can be used to have an 
>>> automatic close action:
>>> ```
>>>     with open("x.txt") as file:
>>>         #do something with file
>>>     #`file.close()` called automatically
>>> ```
>>>
>>> I know D's `with` statement does something different but is 
>>> there some sort of equivalent?
>>
>> Others have discussed that particular case at length, but to 
>> provide a more generic answer the correct way to translate a 
>> python context manager is to use scope(out):
>>
>>     { // Scope restriction similar to with's block
>>         auto f = File("x.txt");
>>         scope(out) f.close();   // closes f on scope exit no 
>> matter what
>>
>>         /* do stuff with f */
>>     }
>>
>> This accurately reproduces the behaviour of python's with 
>> although it's less automatic.
>
> I know that I am repeating myself, but manually closing the 
> file isn't needed in D. It's refCounted and will be closed 
> automatically once the scope is left. That's why 
> `with(File("AAA","w"))` works in D.

As stated, yes that's an accurate answer to that particular 
problem and it's well understood, I'm just giving a more general 
answer that will work for every python context manager and not 
only on the  specific case of closing files.


More information about the Digitalmars-d-learn mailing list