Skip to content

Commit 7ad9048

Browse files
committed
review changes 1
- Added comments and Changelog - reverted additional changes - reverted micro optims
1 parent f2c7b3e commit 7ad9048

10 files changed

Lines changed: 41 additions & 31 deletions

File tree

CHANGES.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,7 @@
120120
splicing the unchanged blocks into each parent's child list in a single pass rather
121121
than removing and re-inserting each one, which rescanned and shifted the whole child
122122
list on every conversion (#5213)
123+
- Reduce memory requirement for Node and Leaf class (#5222)
123124

124125
### Output
125126

src/black/brackets.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,7 @@ def delimiter_count_with_priority(self, priority: Priority = 0) -> int:
156156
return 0
157157

158158
priority = priority or self.max_delimiter_priority()
159-
return sum(p == priority for p in self.delimiters.values())
159+
return sum(1 for p in self.delimiters.values() if p == priority)
160160

161161
def maybe_increment_for_loop_variable(self, leaf: Leaf) -> bool:
162162
"""In a for loop, or comprehension, the variables are often unpacks.

src/black/comments.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
from collections.abc import Collection, Iterator
33
from dataclasses import dataclass
44
from functools import lru_cache
5-
from typing import Final
5+
from typing import Final, Union
66

77
from black.mode import Mode
88
from black.nodes import (
@@ -22,7 +22,7 @@
2222
from blib2to3.pytree import Leaf, Node
2323

2424
# types
25-
LN = Leaf | Node
25+
LN = Union[Leaf, Node]
2626

2727
FMT_OFF: Final = {"# fmt: off", "# fmt:off", "# yapf: disable"}
2828
FMT_SKIP: Final = {"# fmt: skip", "# fmt:skip"}

src/black/handle_ipynb_magics.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -460,7 +460,9 @@ def visit_Assign(self, node: ast.Assign) -> None:
460460
if node.value.func.attr == "getoutput":
461461
src = f"!{args[0]}"
462462
elif node.value.func.attr == "run_line_magic":
463-
src = "%" + " ".join(filter(None, args))
463+
src = f"%{args[0]}"
464+
if args[1]:
465+
src += f" {args[1]}"
464466
else:
465467
raise AssertionError(
466468
f"Unexpected IPython magic {node.value.func.attr!r} found. "
@@ -498,7 +500,9 @@ def visit_Expr(self, node: ast.Expr) -> None:
498500
elif args[0] == "pinfo2":
499501
src = f"??{args[1]}"
500502
else:
501-
src = "%" + " ".join(filter(None, args))
503+
src = f"%{args[0]}"
504+
if args[1]:
505+
src += f" {args[1]}"
502506
elif node.value.func.attr == "system":
503507
src = f"!{args[0]}"
504508
elif node.value.func.attr == "getoutput":

src/black/lines.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -197,9 +197,7 @@ def _is_triple_quoted_string(self) -> bool:
197197
if not self or self.leaves[0].type != token.STRING:
198198
return False
199199
value = self.leaves[0].value
200-
if value.startswith(('"""', "'''")):
201-
return True
202-
return value.startswith(("r'''", 'r"""', "R'''", 'R"""'))
200+
return value.startswith(('"""', "'''", "r'''", 'r"""', "R'''", 'R"""'))
203201

204202
@property
205203
def is_docstring(self) -> bool:
@@ -481,9 +479,9 @@ def __str__(self) -> str:
481479
return "\n"
482480

483481
indent = " " * self.depth
484-
first, *rest = self.leaves
482+
first = self.leaves[0]
485483

486-
rest_str = "".join(map(str, rest))
484+
rest_str = "".join(map(str, self.leaves[1:]))
487485
comments_str = "".join(
488486
str(comment) for group in self.comments.values() for comment in group
489487
)
@@ -1607,6 +1605,7 @@ def can_omit_invisible_parens(
16071605
# a leading opening bracket and a trailing closing bracket. If the
16081606
# opening bracket doesn't match our rule, maybe the closing will.
16091607

1608+
penultimate = line.leaves[-2]
16101609
last = line.leaves[-1]
16111610

16121611
if (
@@ -1620,7 +1619,6 @@ def can_omit_invisible_parens(
16201619
and last.parent.type != syms.trailer
16211620
)
16221621
):
1623-
penultimate = line.leaves[-2]
16241622
if penultimate.type in OPENING_BRACKETS:
16251623
# Empty brackets don't help.
16261624
return False

src/black/output.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,9 @@ def color_diff(contents: str) -> str:
112112

113113

114114
def style_output(message: str, **styles: Any) -> str:
115-
return style(message, **styles) if _color_enabled() else message
115+
if not _color_enabled():
116+
return message
117+
return style(message, **styles)
116118

117119

118120
def _color_enabled() -> bool:

src/black/trans.py

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -360,7 +360,7 @@ def _get_key(string: str) -> CustomSplitMapKey:
360360
A unique identifier that is used internally to map @string to a
361361
group of custom splits.
362362
"""
363-
return id(string), string
363+
return (id(string), string)
364364

365365
def add_custom_splits(
366366
self, string: str, custom_splits: Iterable[CustomSplit]
@@ -1018,11 +1018,13 @@ def do_transform(
10181018
string_parser = StringParser()
10191019
rpar_idx = string_parser.parse(LL, string_idx)
10201020

1021-
# Should not strip parentheses which have comments attached
1022-
# to them.
1023-
should_transform = not any(
1024-
line.comments_after(leaf) for leaf in (LL[string_idx - 1], LL[rpar_idx])
1025-
)
1021+
should_transform = True
1022+
for leaf in (LL[string_idx - 1], LL[rpar_idx]):
1023+
if line.comments_after(leaf):
1024+
# Should not strip parentheses which have comments attached
1025+
# to them.
1026+
should_transform = False
1027+
break
10261028
if should_transform:
10271029
string_and_rpar_indices.extend((string_idx, rpar_idx))
10281030

@@ -1358,7 +1360,7 @@ def iter_fexpr_spans(s: str) -> Iterator[tuple[int, int]]:
13581360
j = stack.pop()
13591361
# we've made it back out of the expression! yield the span
13601362
if not stack:
1361-
yield j, i + 1
1363+
yield (j, i + 1)
13621364
i += 1
13631365
continue
13641366

src/blib2to3/pgen2/conv.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -168,7 +168,7 @@ def parse_graminit_c(self, filename):
168168
mo = re.match(r"static dfa dfas\[(\d+)\] = {$", line)
169169
assert mo, (lineno, line)
170170
ndfas = int(mo.group(1))
171-
for _ in range(ndfas):
171+
for i in range(ndfas):
172172
lineno, line = lineno + 1, next(f)
173173
mo = re.match(r'\s+{(\d+), "(\w+)", (\d+), (\d+), states_(\d+),$', line)
174174
assert mo, (lineno, line)

src/blib2to3/pgen2/pgen.py

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,13 @@
22
# Licensed to PSF under a Contributor Agreement.
33

44
import os
5-
from collections.abc import Iterator
6-
from typing import IO, Any, NoReturn
5+
from collections.abc import Iterator, Sequence
6+
from typing import IO, Any, NoReturn, Union
77

88
from blib2to3.pgen2 import grammar, token, tokenize
99
from blib2to3.pgen2.tokenize import TokenInfo
1010

11-
Path = str | os.PathLike[str]
11+
Path = Union[str, "os.PathLike[str]"]
1212

1313

1414
class PgenGrammar(grammar.Grammar):
@@ -144,7 +144,7 @@ def calcfirst(self, name: str) -> None:
144144
self.calcfirst(label)
145145
fset = self.first[label]
146146
assert fset is not None
147-
totalset |= fset
147+
totalset.update(fset)
148148
overlapcheck[label] = fset
149149
else:
150150
totalset[label] = 1
@@ -374,7 +374,10 @@ def __eq__(self, other: Any) -> bool:
374374
# would invoke this method recursively, with cycles...
375375
if len(self.arcs) != len(other.arcs):
376376
return False
377-
return all(next_ is other.arcs.get(label) for label, next_ in self.arcs.items())
377+
for label, next in self.arcs.items():
378+
if next is not other.arcs.get(label):
379+
return False
380+
return True
378381

379382
__hash__: Any = None # For Py3 compatibility.
380383

src/blib2to3/pytree.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -65,9 +65,9 @@ class Base(ABC):
6565
__slots__ = ("type", "parent", "children", "was_changed")
6666

6767
def __init__(self, type_id: int, children: Optional[list[NL]] = None):
68-
self.type = type_id
69-
self.children = children or []
70-
self.parent: Optional["Node"] = None
68+
self.type = type_id # int: token number (< 256) or symbol number (>= 256)
69+
self.children = children or [] # List of subnodes
70+
self.parent: Optional["Node"] = None # Parent node pointer, or None
7171
self.was_changed: bool = False
7272

7373
def __eq__(self, other: Any) -> bool:
@@ -618,7 +618,7 @@ def match(self, node: NL, results: _Results | None = None) -> bool:
618618
return False
619619
if r:
620620
assert results is not None
621-
results |= r
621+
results.update(r)
622622
if results is not None and self.name:
623623
results[self.name] = node
624624
return True
@@ -749,7 +749,7 @@ def _submatch(self, node, results=None) -> bool:
749749
for c, r in generate_matches(self.content, node.children):
750750
if c == len(node.children):
751751
if results is not None:
752-
results |= r
752+
results.update(r)
753753
return True
754754
return False
755755
if len(self.content) != len(node.children):
@@ -856,7 +856,7 @@ def match_seq(self, nodes, results=None) -> bool:
856856
for c, r in self.generate_matches(nodes):
857857
if c == len(nodes):
858858
if results is not None:
859-
results |= r
859+
results.update(r)
860860
if self.name:
861861
results[self.name] = list(nodes)
862862
return True

0 commit comments

Comments
 (0)