Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add basic with/as grammar #4

Merged
merged 2 commits into from Sep 5, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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")