Last active
December 31, 2015 09:09
-
-
Save gradha/7964832 to your computer and use it in GitHub Desktop.
Python's with statement implemented in Nimrod
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import macros | |
| macro with_closing*(opening, holder: expr, body: stmt): stmt {.immediate.} = | |
| var code = newNimNode(nnkStmtList) | |
| var def = newNimNode(nnkVarSection) | |
| # Create the variable assignment, holder + opening | |
| var idents = newIdentDefs(holder, newEmptyNode()) | |
| idents[2] = opening | |
| def.add(idents) | |
| code.add(def) | |
| # Create the try block and insert the body statements. | |
| var tr = newNimNode(nnkTryStmt) | |
| tr.add(body) | |
| # Now create a finally block which invokes close() on the holder. | |
| var fin = newNimNode(nnkFinally) | |
| fin.add(newStmtList(newCall(newIdentNode("close"), holder))) | |
| tr.add(fin) | |
| code.add(tr) | |
| result = newBlockStmt(code) | |
| with_closing(Open("test.txt", fmWrite), f): | |
| f.write("Hey there\n") | |
| f.write("This looks nice!") | |
| echo "Hey" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment