Skip to content

Commit

Permalink
Merge pull request #4 from yuchunzhou/master
Browse files Browse the repository at this point in the history
add basic with/as grammar
  • Loading branch information
Adam Chesak committed Sep 5, 2019
2 parents 29913f1 + d94c638 commit 4852536
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 2 deletions.
5 changes: 5 additions & 0 deletions README.md
Expand Up @@ -28,6 +28,11 @@ Examples:
f.write("Inserted at pos 50 from end") # f.write("Inserted at pos 50 from end")
f.close() # f.close()

# Basic with/as grammer for file operation
with open("temp.txt", "w+") as f:
f.write("test")
f.seek(0, 0)
echo(f.read())

Note that due to some inherent differences between how Nim and Python handle files, a complete
1 to 1 wrapper is not possible. Notably, Nim has no equivalent to the `newlines` and `encoding`
Expand Down
45 changes: 43 additions & 2 deletions pythonfile.nim
Expand Up @@ -47,7 +47,7 @@
## For general use, however, this wrapper provides all of the common Python file methods.


import strutils, terminal
import macros, strutils, terminal


type
Expand All @@ -61,6 +61,36 @@ type
newlines*: string
filename*: string

macro with*(args: untyped, body: untyped): untyped =
### A with macro.

args.expectKind nnkInfix
args.expectLen 3

# basic stmt
var stmt = newStmtList()
stmt.add newTree(nnkVarSection,
newIdentDefs(
args[2],
newEmptyNode(),
args[1]
)
)

for i in body: stmt.add i
stmt.add newTree(nnkCall,
newDotExpr(
args[2],
newIdentNode("close")
)
)

# add basic stmt to block stmt, for better exception catch
result = newStmtList()
result.add newTree(nnkBlockStmt,
newEmptyNode(),
stmt
)

proc open*(filename: string, mode: string = "r", buffering: int = -1): PythonFile =
## Opens the specified file.
Expand Down Expand Up @@ -273,4 +303,15 @@ proc writelines*(file: PythonFile, lines: openarray[string]): void =
proc isatty*(file: PythonFile): bool =
## Returns true if the opened file is a tty device, else returns false

return file.f.isatty()
return file.f.isatty()


when isMainModule:
## test code
with open("temp.txt", "w+") as f:
f.write("test")
f.seek(0, 0)
echo(f.read())

import os
os.removeFile("temp.txt")

0 comments on commit 4852536

Please sign in to comment.