Skip to content

Commit 7d59112

Browse files
committed
type: add type annotations to math.py
Add type annotations to math parsing and transformation functions. Changes: - Add types to join_math_block(), parse_math(), join_math_text() - Add types to extract_math() - Use ASTNode and ASTNodes type aliases
1 parent b3542a9 commit 7d59112

File tree

1 file changed

+11
-8
lines changed

1 file changed

+11
-8
lines changed

md2zhihu/parser/transform/math.py

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
import re
22

3+
from ...types import ASTNode
4+
from ...types import ASTNodes
35

4-
def join_math_block(nodes):
6+
7+
def join_math_block(nodes: ASTNodes) -> None:
58
"""
69
A tex segment may spans several paragraph:
710
@@ -21,13 +24,13 @@ def join_math_block(nodes):
2124
join_math_text(nodes)
2225

2326

24-
def parse_math(nodes):
27+
def parse_math(nodes: ASTNodes) -> ASTNodes:
2528
"""
2629
Extract all math segment such as ``$$ ... $$`` from a text and build a
2730
math_block or math_inline node.
2831
"""
2932

30-
children = []
33+
children: ASTNodes = []
3134

3235
for n in nodes:
3336
if "children" in n:
@@ -42,7 +45,7 @@ def parse_math(nodes):
4245
return children
4346

4447

45-
def join_math_text(nodes):
48+
def join_math_text(nodes: ASTNodes) -> None:
4649
i = 0
4750
while i < len(nodes) - 1:
4851
n1 = nodes[i]
@@ -68,27 +71,27 @@ def join_math_text(nodes):
6871
i += 1
6972

7073

71-
def extract_math(n):
74+
def extract_math(n: ASTNode) -> ASTNodes:
7275
"""
7376
Extract ``$$ ... $$`` or ``$ .. $` from a text node and build a new node.
7477
The original text node is split into multiple segments.
7578
7679
The math is a block if it is a paragraph.
7780
Otherwise, it is an inline math.
7881
"""
79-
children = []
82+
children: ASTNodes = []
8083

8184
math_regex = r"([$]|[$][$])([^$].*?)\1"
8285

83-
t = n["text"]
86+
t: str = n["text"]
8487
while True:
8588
match = re.search(math_regex, t, flags=re.DOTALL)
8689
if match:
8790
children.append({"type": "text", "text": t[: match.start()]})
8891
children.append({"type": "math_inline", "text": match.groups()[1]})
8992
t = t[match.end() :]
9093

91-
left = children[-2]["text"]
94+
left: str = children[-2]["text"]
9295
right = t
9396
if (left == "" or left.endswith("\n\n")) and (right == "" or right.startswith("\n")):
9497
children[-1]["type"] = "math_block"

0 commit comments

Comments
 (0)