Hi there.
I like the Python RAII pattern of "with" statements, alongside context managers.
eg, this is nice:
with open("test.txt") as f:
print f.read()
Closest thing to that I could find was the "withFile" example over in the
second Nim tut.
So I've tried to adapt that example a bit, and ended up with this:
template withAs(x: typed, y: untyped,
body: untyped): typed =
var x2 = x
var y = x2.enter()
try:
body
finally:
exit(x2)
proc enter(f: File): File =
echo "Entering context manager"
return f
proc exit(f: File) =
echo "Leaving context manager"
f.close()
open("test.txt").withAs(txt):
echo txt.readLine()
So when I run that, I get this output:
Entering context manager
HOW ARE YOU GENTLEMEN
Leaving context manager
So it looks like things are working.
Is "withAs" (and context managers) an existing well-known Nim pattern?
Would be nice to be able to eg, do "nim install contextlib", and then have
"withAs" as well as some other useful things.
Comments?