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

if lines is used once, define it as a generator #23

Closed
wants to merge 2 commits into from
Closed
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion pyp.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ def __init__(self, *trees: ast.AST) -> None:
self._scopes: List[Set[str]] = [set()]
self.undefined: Set[str] = set()
self.wildcard_imports: List[str] = []
self.lines_count = 0
for tree in trees:
self.visit(tree)
assert len(self._scopes) == 1
Expand All @@ -80,6 +81,8 @@ def order(f_v: Tuple[str, Any]) -> int:
self.flexible_visit(value)

def visit_Name(self, node: ast.Name) -> None:
if node.id in ("lines"):
self.lines_count += 1
if isinstance(node.ctx, ast.Load):
if all(node.id not in d for d in self._scopes):
self.undefined.add(node.id)
Expand Down Expand Up @@ -276,7 +279,7 @@ def parse_input(code: List[str]) -> ast.Module:
self.defined: Set[str] = f.top_level_defined
self.undefined: Set[str] = f.undefined
self.wildcard_imports: List[str] = f.wildcard_imports

self.lines_count = f.lines_count
self.define_pypprint = define_pypprint
self.config = config

Expand Down Expand Up @@ -417,6 +420,9 @@ def build_input(self) -> None:

if input_var == "stdin":
input_assign = ast.parse(f"{input_var} = sys.stdin")
elif self.lines_count == 1:
# little optimization. If lines is used once, we can define it as a generator and consume it
input_assign = ast.parse(f"{input_var} = (x.rstrip('\\n') for x in sys.stdin)")
else:
input_assign = ast.parse(f"{input_var} = [x.rstrip('\\n') for x in sys.stdin]")

Expand Down