Skip to content

Commit 927e190

Browse files
committed
move edit in __init__
1 parent c7a63e4 commit 927e190

File tree

4 files changed

+40
-41
lines changed

4 files changed

+40
-41
lines changed

pythoned/__init__.py

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,38 @@
1-
from pythoned.edit import edit
1+
import importlib
2+
import os
3+
import re
4+
from types import ModuleType
5+
from typing import Dict, Iterator
6+
7+
8+
_TYPE_ERROR_MSG = "The provided expression must be an str (editing) or a bool (filtering), but got {}."
9+
10+
11+
def edit(lines: Iterator[str], expression) -> Iterator[str]:
12+
modules: Dict[str, ModuleType] = {}
13+
for line in lines:
14+
linesep = ""
15+
if line.endswith(os.linesep):
16+
linesep, line = os.linesep, line[: -len(os.linesep)]
17+
globals = {"_": line, **modules}
18+
try:
19+
value = eval(expression, globals)
20+
except NameError as name_error:
21+
match = re.match(r"name '([A-Za-z]+)'.*", str(name_error))
22+
if match:
23+
module = match.group(1)
24+
else:
25+
raise name_error
26+
try:
27+
modules[module] = importlib.import_module(module)
28+
globals = {"_": line, **modules}
29+
except:
30+
raise name_error
31+
value = eval(expression, globals)
32+
if isinstance(value, str):
33+
yield value + linesep
34+
elif isinstance(value, bool):
35+
if value:
36+
yield line + linesep
37+
else:
38+
raise TypeError(_TYPE_ERROR_MSG.format(type(value)))

pythoned/__main__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import argparse
22
import sys
33

4-
from pythoned.edit import edit
4+
from pythoned import edit
55

66

77
def main() -> int:

pythoned/edit.py

Lines changed: 0 additions & 38 deletions
This file was deleted.

tests/test.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
from typing import Iterator
22
import unittest
33

4-
from pythoned.edit import edit
4+
from pythoned import edit
55

66

77
def lines() -> Iterator[str]:

0 commit comments

Comments
 (0)