Skip to content

Commit efda73a

Browse files
committed
refactor: Type hinting update
1 parent b70dc37 commit efda73a

File tree

9 files changed

+50
-62
lines changed

9 files changed

+50
-62
lines changed

pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ classifiers = [
2727
"Topic :: Utilities",
2828
]
2929

30-
requires-python = ">=3.8"
30+
requires-python = ">=3.12"
3131
dependencies = [
3232
"Sphinx >= 4",
3333
"langid",

src/sphinxnotes/snippet/cache.py

Lines changed: 15 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
"""
77

88
from __future__ import annotations
9-
from typing import List, Tuple, Dict, Optional
109
from dataclasses import dataclass
1110

1211
from .snippets import Snippet
@@ -18,25 +17,25 @@ class Item(object):
1817
"""Item of snippet cache."""
1918

2019
snippet: Snippet
21-
tags: List[str]
20+
tags: list[str]
2221
excerpt: str
23-
titlepath: List[str]
24-
keywords: List[str]
22+
titlepath: list[str]
23+
keywords: list[str]
2524

2625

27-
DocID = Tuple[str, str] # (project, docname)
26+
DocID = tuple[str, str] # (project, docname)
2827
IndexID = str # UUID
29-
Index = Tuple[str, str, List[str], List[str]] # (tags, excerpt, titlepath, keywords)
28+
Index = tuple[str, str, list[str], list[str]] # (tags, excerpt, titlepath, keywords)
3029

3130

3231
class Cache(PDict):
33-
"""A DocID -> List[Item] Cache."""
32+
"""A DocID -> list[Item] Cache."""
3433

35-
indexes: Dict[IndexID, Index]
36-
index_id_to_doc_id: Dict[IndexID, Tuple[DocID, int]]
37-
doc_id_to_index_ids: Dict[DocID, List[IndexID]]
38-
num_snippets_by_project: Dict[str, int]
39-
num_snippets_by_docid: Dict[DocID, int]
34+
indexes: dict[IndexID, Index]
35+
index_id_to_doc_id: dict[IndexID, tuple[DocID, int]]
36+
doc_id_to_index_ids: dict[DocID, list[IndexID]]
37+
num_snippets_by_project: dict[str, int]
38+
num_snippets_by_docid: dict[DocID, int]
4039

4140
def __init__(self, dirname: str) -> None:
4241
self.indexes = {}
@@ -46,7 +45,7 @@ def __init__(self, dirname: str) -> None:
4645
self.num_snippets_by_docid = {}
4746
super().__init__(dirname)
4847

49-
def post_dump(self, key: DocID, items: List[Item]) -> None:
48+
def post_dump(self, key: DocID, items: list[Item]) -> None:
5049
"""Overwrite PDict.post_dump."""
5150

5251
# Remove old indexes and index IDs if exists
@@ -74,7 +73,7 @@ def post_dump(self, key: DocID, items: List[Item]) -> None:
7473
self.num_snippets_by_docid[key] = 0
7574
self.num_snippets_by_docid[key] += len(items)
7675

77-
def post_purge(self, key: DocID, items: List[Item]) -> None:
76+
def post_purge(self, key: DocID, items: list[Item]) -> None:
7877
"""Overwrite PDict.post_purge."""
7978

8079
# Purge indexes
@@ -90,7 +89,7 @@ def post_purge(self, key: DocID, items: List[Item]) -> None:
9089
if self.num_snippets_by_docid[key] == 0:
9190
del self.num_snippets_by_docid[key]
9291

93-
def get_by_index_id(self, key: IndexID) -> Optional[Item]:
92+
def get_by_index_id(self, key: IndexID) -> Item | None:
9493
"""Like get(), but use IndexID as key."""
9594
doc_id, item_index = self.index_id_to_doc_id.get(key, (None, None))
9695
if not doc_id:
@@ -103,6 +102,6 @@ def gen_index_id(self) -> str:
103102

104103
return uuid.uuid4().hex[:7]
105104

106-
def stringify(self, key: DocID, items: List[Item]) -> str:
105+
def stringify(self, key: DocID, items: list[Item]) -> str:
107106
"""Overwrite PDict.stringify."""
108107
return key[1]

src/sphinxnotes/snippet/cli.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
import os
1717
from os import path
1818
import argparse
19-
from typing import List, Iterable, Tuple
19+
from typing import Iterable
2020
from textwrap import dedent
2121
from shutil import get_terminal_size
2222
import posixpath
@@ -51,7 +51,7 @@ def get_integration_file(fn: str) -> str:
5151
return path.join(prefix, 'integration', fn)
5252

5353

54-
def main(argv: List[str] = sys.argv[1:]):
54+
def main(argv: list[str] = sys.argv[1:]):
5555
"""Command line entrypoint."""
5656

5757
parser = argparse.ArgumentParser(
@@ -237,7 +237,7 @@ def _on_command_stat(args: argparse.Namespace):
237237

238238
def _filter_list_items(
239239
cache: Cache, tags: str, docname_glob: str
240-
) -> Iterable[Tuple[IndexID, Index]]:
240+
) -> Iterable[tuple[IndexID, Index]]:
241241
# NOTE: Importing is slow, do it on demand.
242242
from sphinx.util.matching import patmatch
243243

src/sphinxnotes/snippet/ext.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
"""
1010

1111
from __future__ import annotations
12-
from typing import List, Set, TYPE_CHECKING, Dict
12+
from typing import TYPE_CHECKING
1313
import re
1414
from os import path
1515
import time
@@ -56,7 +56,7 @@ def extract_excerpt(s: Snippet) -> str:
5656
return ''
5757

5858

59-
def extract_keywords(s: Snippet) -> List[str]:
59+
def extract_keywords(s: Snippet) -> list[str]:
6060
keywords = [s.docname]
6161
# TODO: Deal with more snippet
6262
if isinstance(s, WithTitle) and s.title is not None:
@@ -65,8 +65,8 @@ def extract_keywords(s: Snippet) -> List[str]:
6565

6666

6767
def is_document_matched(
68-
pats: Dict[str, List[str]], docname: str
69-
) -> Dict[str, List[str]]:
68+
pats: dict[str, list[str]], docname: str
69+
) -> dict[str, list[str]]:
7070
"""Whether the docname matched by given patterns pats"""
7171
new_pats = {}
7272
for tag, ps in pats.items():
@@ -76,7 +76,7 @@ def is_document_matched(
7676
return new_pats
7777

7878

79-
def is_snippet_matched(pats: Dict[str, List[str]], s: [Snippet], docname: str) -> bool:
79+
def is_snippet_matched(pats: dict[str, list[str]], s: [Snippet], docname: str) -> bool:
8080
"""Whether the snippet's tags and docname matched by given patterns pats"""
8181
if '*' in pats: # Wildcard
8282
for pat in pats['*']:
@@ -108,10 +108,10 @@ def on_config_inited(app: Sphinx, appcfg: SphinxConfig) -> None:
108108
def on_env_get_outdated(
109109
app: Sphinx,
110110
env: BuildEnvironment,
111-
added: Set[str],
112-
changed: Set[str],
113-
removed: Set[str],
114-
) -> List[str]:
111+
added: set[str],
112+
changed: set[str],
113+
removed: set[str],
114+
) -> list[str]:
115115
# Remove purged indexes and snippetes from db
116116
for docname in removed:
117117
del cache[(app.config.project, docname)]

src/sphinxnotes/snippet/keyword.py

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@
99
"""
1010

1111
from __future__ import annotations
12-
from typing import List, Optional
1312
import string
1413
from collections import Counter
1514

@@ -47,8 +46,8 @@ def __init__(self):
4746
)
4847

4948
def extract(
50-
self, text: str, top_n: Optional[int] = None, strip_stopwords: bool = True
51-
) -> List[str]:
49+
self, text: str, top_n: int | None = None, strip_stopwords: bool = True
50+
) -> list[str]:
5251
"""Return keywords of given text."""
5352
# TODO: zh -> en
5453
# Normalize
@@ -87,7 +86,7 @@ def normalize(self, text: str) -> str:
8786
text = text.replace('\n', ' ')
8887
return text
8988

90-
def tokenize(self, text: str) -> List[str]:
89+
def tokenize(self, text: str) -> list[str]:
9190
# Get top most 5 langs
9291
langs = self._detect_langs(text)[:5]
9392
tokens = [text]
@@ -104,16 +103,16 @@ def tokenize(self, text: str) -> List[str]:
104103
new_tokens = []
105104
return tokens
106105

107-
def trans_to_pinyin(self, word: str) -> Optional[str]:
106+
def trans_to_pinyin(self, word: str) -> str | None:
108107
return ' '.join(self._pinyin(word, errors='ignore'))
109108

110-
def strip_stopwords(self, words: List[str]) -> List[str]:
109+
def strip_stopwords(self, words: list[str]) -> list[str]:
111110
stw = self._stopwords(['en', 'zh'])
112111
new_words = []
113112
for word in words:
114113
if word not in stw:
115114
new_words.append(word)
116115
return new_words
117116

118-
def strip_invalid_token(self, tokens: List[str]) -> List[str]:
117+
def strip_invalid_token(self, tokens: list[str]) -> list[str]:
119118
return [token for token in tokens if token != '']

src/sphinxnotes/snippet/snippets.py

Lines changed: 8 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
"""
1010

1111
from __future__ import annotations
12-
from typing import List, Tuple, Optional, TYPE_CHECKING
12+
from typing import TYPE_CHECKING
1313
import itertools
1414
from os import path
1515

@@ -36,16 +36,16 @@ class Snippet(object):
3636

3737
#: Line number range of snippet, in the source file which is left closed
3838
#: and right opened.
39-
lineno: Tuple[int, int]
39+
lineno: tuple[int, int]
4040

4141
#: The original reStructuredText of snippet
42-
rst: List[str]
42+
rst: list[str]
4343

4444
#: The possible identifier key of snippet, which is picked from nodes'
4545
#: (or nodes' parent's) `ids attr`_.
4646
#:
4747
#: .. _ids attr: https://docutils.sourceforge.io/docs/ref/doctree.html#ids
48-
refid: Optional[str]
48+
refid: str | None
4949

5050
def __init__(self, *nodes: nodes.Node) -> None:
5151
assert len(nodes) != 0
@@ -94,11 +94,11 @@ def __init__(self, node: nodes.Node) -> None:
9494
self.text = node.astext()
9595

9696

97-
class CodeBlock(Text):
97+
class Code(Text):
9898
#: Language of code block
9999
language: str
100100
#: Caption of code block
101-
caption: Optional[str]
101+
caption: str | None
102102

103103
def __init__(self, node: nodes.literal_block) -> None:
104104
assert isinstance(node, nodes.literal_block)
@@ -107,23 +107,14 @@ def __init__(self, node: nodes.literal_block) -> None:
107107
self.caption = node.get('caption')
108108

109109

110-
class WithCodeBlock(object):
111-
code_blocks: List[CodeBlock]
112-
113-
def __init__(self, nodes: nodes.Nodes) -> None:
114-
self.code_blocks = []
115-
for n in nodes.traverse(nodes.literal_block):
116-
self.code_blocks.append(self.CodeBlock(n))
117-
118-
119110
class Title(Text):
120111
def __init__(self, node: nodes.title) -> None:
121112
assert isinstance(node, nodes.title)
122113
super().__init__(node)
123114

124115

125116
class WithTitle(object):
126-
title: Optional[Title]
117+
title: Title | None
127118

128119
def __init__(self, node: nodes.Node) -> None:
129120
title_node = node.next_node(nodes.title)
@@ -178,7 +169,7 @@ def _line_of_start(node: nodes.Node) -> int:
178169
return node.line
179170

180171

181-
def _line_of_end(node: nodes.Node) -> Optional[int]:
172+
def _line_of_end(node: nodes.Node) -> int | None:
182173
next_node = node.next_node(descend=False, siblings=True, ascend=True)
183174
while next_node:
184175
if next_node.line:

src/sphinxnotes/snippet/table.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
"""
88

99
from __future__ import annotations
10-
from typing import Iterable, Tuple
10+
from typing import Iterable
1111

1212
from .cache import Index, IndexID
1313
from .utils import ellipsis
@@ -17,7 +17,7 @@
1717
COLUMN_DELIMITER = ' '
1818

1919

20-
def tablify(indexes: Iterable[Tuple[IndexID, Index]], width: int) -> Iterable[str]:
20+
def tablify(indexes: Iterable[tuple[IndexID, Index]], width: int) -> Iterable[str]:
2121
"""Create a table from sequence of indices"""
2222

2323
# Calcuate width

src/sphinxnotes/snippet/utils/ellipsis.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,11 @@
99
"""
1010

1111
from __future__ import annotations
12-
from typing import List
1312
from wcwidth import wcswidth
1413

1514

1615
def ellipsis(
17-
text: str, width: int, ellipsis_sym: str = '..', blank_sym: str = None
16+
text: str, width: int, ellipsis_sym: str = '..', blank_sym: str | None = None
1817
) -> str:
1918
text_width = wcswidth(text)
2019
if text_width <= width:
@@ -34,7 +33,7 @@ def ellipsis(
3433

3534

3635
def join(
37-
lst: List[str],
36+
lst: list[str],
3837
total_width: int,
3938
title_width: int,
4039
separate_sym: str = '/',

src/sphinxnotes/snippet/utils/titlepath.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
"""
1010

1111
from __future__ import annotations
12-
from typing import List, TYPE_CHECKING
12+
from typing import TYPE_CHECKING
1313

1414
from docutils import nodes
1515

@@ -19,11 +19,11 @@
1919

2020
def resolve(
2121
env: BuilderEnviornment, docname: str, node: nodes.Node
22-
) -> List[nodes.title]:
22+
) -> list[nodes.title]:
2323
return resolve_section(node) + resolve_document(env, docname)
2424

2525

26-
def resolve_section(node: nodes.section) -> List[nodes.title]:
26+
def resolve_section(node: nodes.section) -> list[nodes.title]:
2727
# FIXME: doc is None
2828
titlenodes = []
2929
while node:
@@ -33,7 +33,7 @@ def resolve_section(node: nodes.section) -> List[nodes.title]:
3333
return titlenodes
3434

3535

36-
def resolve_document(env: BuilderEnviornment, docname: str) -> List[nodes.title]:
36+
def resolve_document(env: BuilderEnviornment, docname: str) -> list[nodes.title]:
3737
"""
3838
.. note:: Title of document itself does not included in the returned list
3939
"""

0 commit comments

Comments
 (0)