Skip to content

Commit 38a1fb3

Browse files
committed
refactor: Type hints cleanup
1 parent 4dc9952 commit 38a1fb3

File tree

8 files changed

+50
-80
lines changed

8 files changed

+50
-80
lines changed

src/sphinxnotes/any/directives.py

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,9 @@
1111
from typing import Type
1212

1313
from docutils import nodes
14+
from docutils.nodes import Node, Element, fully_normalize_name
1415
from docutils.statemachine import StringList
1516
from docutils.parsers.rst import directives
16-
from docutils.nodes import fully_normalize_name
1717

1818
from sphinx import addnodes
1919
from sphinx.util.docutils import SphinxDirective
@@ -81,10 +81,7 @@ def _build_object(self) -> Object:
8181
content='\n'.join(list(self.content.data)))
8282

8383

84-
def _setup_nodes(self, obj:Object,
85-
sectnode:nodes.Element,
86-
ahrnode:nodes.Element|None,
87-
contnode:nodes.Element) -> None:
84+
def _setup_nodes(self, obj:Object, sectnode:Element, ahrnode:Element|None, contnode:Element) -> None:
8885
"""
8986
Attach necessary informations to nodes and note them.
9087
@@ -127,7 +124,7 @@ def _setup_nodes(self, obj:Object,
127124
contnode)
128125

129126

130-
def _run_section(self, obj:Object) -> list[nodes.Node]:
127+
def _run_section(self, obj:Object) -> list[Node]:
131128
# Get the title of the "section" where the directive is located
132129
sectnode = self.state.parent
133130
titlenode = sectnode.next_node(nodes.title)
@@ -156,7 +153,7 @@ def _run_section(self, obj:Object) -> list[nodes.Node]:
156153
return []
157154

158155

159-
def _run_objdesc(self, obj:Object) -> list[nodes.Node]:
156+
def _run_objdesc(self, obj:Object) -> list[Node]:
160157
descnode = addnodes.desc()
161158

162159
# Generate signature node
@@ -179,7 +176,7 @@ def _run_objdesc(self, obj:Object) -> list[nodes.Node]:
179176
return [descnode]
180177

181178

182-
def run(self) -> list[nodes.Node]:
179+
def run(self) -> list[Node]:
183180
obj = self._build_object()
184181
if self.schema.title_of(obj) == '_':
185182
# If no argument is given, or the first argument is '_',

src/sphinxnotes/any/domain.py

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

1111
from __future__ import annotations
12-
from typing import Tuple, Any, Iterator, Type, Set, Optional, TYPE_CHECKING
12+
from typing import Any, Iterator, TYPE_CHECKING
1313

1414
from docutils.nodes import Element, literal, Text
1515

@@ -44,14 +44,14 @@ class AnyDomain(Domain):
4444
#: Type (usually directive) name -> ObjType instance
4545
object_types:dict[str,ObjType]= {}
4646
#: Directive name -> directive class
47-
directives:dict[str,Type[AnyDirective]] = {}
47+
directives:dict[str,type[AnyDirective]] = {}
4848
#: Role name -> role callable
4949
roles:dict[str,RoleFunction] = {}
5050
#: A list of Index subclasses
51-
indices:list[Type[AnyIndex]] = []
52-
#: AnyDomain specific: Type -> index class
53-
_indices_for_reftype:dict[str,Type[AnyIndex]] = {}
54-
#: AnyDomain specific: Type -> Schema instance
51+
indices:list[type[AnyIndex]] = []
52+
#: AnyDomain specific: type -> index class
53+
_indices_for_reftype:dict[str,type[AnyIndex]] = {}
54+
#: AnyDomain specific: type -> Schema instance
5555
_schemas:dict[str,Schema] = {}
5656

5757
initial_data:dict[str,Any] = {
@@ -62,12 +62,12 @@ class AnyDomain(Domain):
6262
}
6363

6464
@property
65-
def objects(self) -> dict[Tuple[str,str], Tuple[str,str,Object]]:
65+
def objects(self) -> dict[tuple[str,str], tuple[str,str,Object]]:
6666
"""(objtype, objid) -> (docname, anchor, obj)"""
6767
return self.data.setdefault('objects', {})
6868

6969
@property
70-
def references(self) -> dict[Tuple[str,str,str],Set[str]]:
70+
def references(self) -> dict[tuple[str,str,str],set[str]]:
7171
"""(objtype, objfield, objref) -> set(objid)"""
7272
return self.data.setdefault('references', {})
7373

@@ -105,7 +105,7 @@ def clear_doc(self, docname:str) -> None:
105105
def resolve_xref(self, env:BuildEnvironment, fromdocname:str,
106106
builder:Builder, typ:str, target:str,
107107
node:pending_xref, contnode:Element,
108-
) -> Optional[Element]:
108+
) -> Element|None:
109109
assert isinstance(contnode, literal)
110110

111111
logger.debug('[any] resolveing xref of %s', (typ, target))
@@ -151,7 +151,7 @@ def resolve_xref(self, env:BuildEnvironment, fromdocname:str,
151151

152152

153153
# Override parent method
154-
def get_objects(self) -> Iterator[Tuple[str, str, str, str, str, int]]:
154+
def get_objects(self) -> Iterator[tuple[str, str, str, str, str, int]]:
155155
for (objtype, objid), (docname, anchor, _) in self.data['objects'].items():
156156
yield objid, objid, objtype, docname, anchor, 1
157157

@@ -186,7 +186,7 @@ def add_schema(cls, schema:Schema) -> None:
186186
cls._indices_for_reftype[r] = index
187187

188188

189-
def _get_index_anchor(self, reftype:str, refval:str) -> Tuple[str,str]:
189+
def _get_index_anchor(self, reftype:str, refval:str) -> tuple[str,str]:
190190
"""
191191
Return the docname and anchor name of index page. Can be used for ``make_refnode()``.
192192
@@ -198,7 +198,7 @@ def _get_index_anchor(self, reftype:str, refval:str) -> Tuple[str,str]:
198198

199199

200200
def warn_missing_reference(app: Sphinx, domain: Domain, node: pending_xref
201-
) -> Optional[bool]:
201+
) -> bool|None:
202202
if domain and domain.name != AnyDomain.name:
203203
return None
204204

@@ -210,7 +210,7 @@ def warn_missing_reference(app: Sphinx, domain: Domain, node: pending_xref
210210
return True
211211

212212

213-
def reftype_to_objtype_and_objfield(reftype:str) -> Tuple[str,Optional[str]]:
213+
def reftype_to_objtype_and_objfield(reftype:str) -> tuple[str,str|None]:
214214
"""Helper function for converting reftype(role name) to object infos."""
215215
v = reftype.split('.', maxsplit=1)
216216
return v[0], v[1] if len(v) == 2 else None

src/sphinxnotes/any/indices.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
:copyright: Copyright 2021 Shengyu Zhang
88
:license: BSD, see LICENSE for details.
99
"""
10-
from typing import Iterable, List, Tuple, Dict, Set, Optional, Type
10+
from typing import Iterable
1111
from sphinx.domains import Index, IndexEntry
1212

1313
from .schema import Schema
@@ -19,14 +19,14 @@ class AnyIndex(Index):
1919

2020
schema:Schema
2121
# TODO: document
22-
field:Optional[str] = None
22+
field:str|None = None
2323

2424
name:str
2525
localname:str
2626
shortname:str
2727

2828
@classmethod
29-
def derive(cls, schema:Schema, field:str|None=None) -> Type["AnyIndex"]:
29+
def derive(cls, schema:Schema, field:str|None=None) -> type["AnyIndex"]:
3030
"""Generate an AnyIndex child class for indexing object."""
3131
if field:
3232
typ = f'Any{schema.objtype.title()}{field.title()}Index'
@@ -45,14 +45,14 @@ def derive(cls, schema:Schema, field:str|None=None) -> Type["AnyIndex"]:
4545

4646

4747
def generate(self, docnames:Iterable[str]|None = None
48-
) -> Tuple[List[Tuple[str,List[IndexEntry]]], bool]:
48+
) -> tuple[list[tuple[str,list[IndexEntry]]], bool]:
4949
"""Override parent method."""
50-
content = {} # type: Dict[str, List[IndexEntry]]
51-
# List of all references
50+
content = {} # type: dict[str, list[IndexEntry]]
51+
# list of all references
5252
objrefs = sorted(self.domain.data['references'].items())
5353

5454
# Reference value -> object IDs
55-
objs_with_same_ref:Dict[str,Set[str]] = {}
55+
objs_with_same_ref:dict[str,set[str]] = {}
5656

5757
for (objtype, objfield, objref), objids in objrefs:
5858
if objtype != self.schema.objtype:

src/sphinxnotes/any/perset.py

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

src/sphinxnotes/any/roles.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@
88
:license: BSD, see LICENSE for details.
99
"""
1010
from __future__ import annotations
11-
from typing import Type
1211

1312
from sphinx.util import logging
1413
from sphinx.roles import XRefRole
@@ -29,7 +28,7 @@ class AnyRole(XRefRole):
2928
schema:Schema
3029

3130
@classmethod
32-
def derive(cls, schema:Schema, field:str|None=None) -> Type["AnyRole"]:
31+
def derive(cls, schema:Schema, field:str|None=None) -> type["AnyRole"]:
3332
"""Generate an AnyRole child class for referencing object."""
3433
return type('Any%s%sRole' % (schema.objtype.title(), field.title() if field else ''),
3534
(cls,),

src/sphinxnotes/any/schema.py

Lines changed: 22 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
:copyright: Copyright 2021 Shengyu Zhang
88
:license: BSD, see LICENSE for details.
99
"""
10-
from typing import Tuple, Dict, Iterator, List, Set, Optional, Union, Any
10+
from typing import Iterator, Any
1111
from enum import Enum, auto
1212
from dataclasses import dataclass
1313
import pickle
@@ -32,7 +32,7 @@ class SchemaError(AnyExtensionError):
3232
class Object(object):
3333
objtype:str
3434
name:str
35-
attrs:Dict[str,str]
35+
attrs:dict[str,str]
3636
content:str
3737

3838
def hexdigest(self) -> str:
@@ -90,20 +90,20 @@ def _as_plain(self, rawval:str) -> str:
9090
return rawval
9191

9292

93-
def _as_words(self, rawval:str) -> List[str]:
93+
def _as_words(self, rawval:str) -> list[str]:
9494
assert self.form == self.Form.WORDS
9595
assert rawval is not None
9696
return [x.strip() for x in rawval.split(' ') if x.strip() != '']
9797

9898

99-
def _as_lines(self, rawval:str) -> List[str]:
99+
def _as_lines(self, rawval:str) -> list[str]:
100100
assert self.form == self.Form.LINES
101101
assert rawval is not None
102102
return rawval.split('\n')
103103

104104

105105

106-
def value_of(self, rawval:Optional[str]) -> Union[None,str,List[str]]:
106+
def value_of(self, rawval:str|None) -> None|str|list[str]:
107107
if rawval is None:
108108
assert not self.required
109109
return None
@@ -139,7 +139,7 @@ class Schema(object):
139139

140140
# Object fields
141141
name:Field
142-
attrs:Dict[str,Field]
142+
attrs:dict[str,Field]
143143
content:Field
144144

145145
# Class-wide shared template environment
@@ -160,9 +160,9 @@ class Schema(object):
160160
ambiguous_reference_template:str
161161

162162
def __init__(self, objtype:str,
163-
name:Optional[Field]=Field(unique=True, referenceable=True),
164-
attrs:Dict[str,Field]={},
165-
content:Optional[Field]=Field(),
163+
name:Field|None=Field(unique=True, referenceable=True),
164+
attrs:dict[str,Field]={},
165+
content:Field|None=Field(),
166166
description_template:str='{{ content }}',
167167
reference_template:str='{{ title }}',
168168
missing_reference_template:str='{{ title }} (missing reference)',
@@ -199,7 +199,7 @@ def __init__(self, objtype:str,
199199
has_unique = field.unique
200200

201201

202-
def object(self, name:Optional[str], attrs:Dict[str,str], content:Optional[str]) -> Object:
202+
def object(self, name:str|None, attrs:dict[str,str], content:str|None) -> Object:
203203
"""Generate a object"""
204204
obj = Object(objtype=self.objtype,
205205
name=name,
@@ -211,11 +211,11 @@ def object(self, name:Optional[str], attrs:Dict[str,str], content:Optional[str])
211211
return obj
212212

213213

214-
def fields_of(self, obj:Object) -> Iterator[Tuple[str,Field,Union[None,str,List[str]]]]:
214+
def fields_of(self, obj:Object) -> Iterator[tuple[str,Field,None|str|list[str]]]:
215215
"""
216216
Helper method for returning all fields of object and its raw values.
217217
-> Iterator[field_name, field_instance, field_value],
218-
while the field_value is Union[string_value, string_list_value].
218+
while the field_value is string_value|string_list_value.
219219
"""
220220
if self.name:
221221
yield (self.NAME_KEY, self.name, self.name.value_of(obj.name) if obj else None)
@@ -225,22 +225,22 @@ def fields_of(self, obj:Object) -> Iterator[Tuple[str,Field,Union[None,str,List[
225225
yield (self.CONTENT_KEY, self.content, self.content.value_of(obj.content) if obj else None)
226226

227227

228-
def name_of(self, obj:Object) -> Union[None,str,List[str]]:
228+
def name_of(self, obj:Object) -> None|str|list[str]:
229229
assert obj
230230
return self.content.value_of(obj.name)
231231

232232

233-
def attrs_of(self, obj:Object) -> Dict[str,Union[None,str,List[str]]]:
233+
def attrs_of(self, obj:Object) -> dict[str,None|str|list[str]]:
234234
assert obj
235235
return {k: f.value_of(obj.attrs.get(k)) for k, f in self.attrs.items()}
236236

237237

238-
def content_of(self, obj:Object) -> Union[None,str,List[str]]:
238+
def content_of(self, obj:Object) -> None|str|list[str]:
239239
assert obj
240240
return self.content.value_of(obj.content)
241241

242242

243-
def identifier_of(self, obj:Object) -> Tuple[Optional[str],str]:
243+
def identifier_of(self, obj:Object) -> tuple[str|None,str]:
244244
"""
245245
Return unique identifier of object.
246246
If there is not any unique field, return (None, obj.hexdigest()) instead.
@@ -259,7 +259,7 @@ def identifier_of(self, obj:Object) -> Tuple[Optional[str],str]:
259259
return None, obj.hexdigest()
260260

261261

262-
def title_of(self, obj:Object) -> Optional[str]:
262+
def title_of(self, obj:Object) -> str|None:
263263
"""Return title (display name) of object."""
264264
assert obj
265265
name = self.name.value_of(obj.name)
@@ -271,7 +271,7 @@ def title_of(self, obj:Object) -> Optional[str]:
271271
return None
272272

273273

274-
def references_of(self, obj:Object) -> Set[Tuple[str,str]]:
274+
def references_of(self, obj:Object) -> set[tuple[str,str]]:
275275
"""Return all references (referenceable fields) of object"""
276276
assert obj
277277
refs = []
@@ -287,16 +287,16 @@ def references_of(self, obj:Object) -> Set[Tuple[str,str]]:
287287
return set(refs)
288288

289289

290-
def _context_without_object(self) -> Dict[str,Union[str,List[str]]]:
290+
def _context_without_object(self) -> dict[str,str|list[str]]:
291291
return {
292292
self.TYPE_KEY: self.objtype,
293293
}
294294

295295

296-
def _context_of(self, obj:Object) -> Dict[str,Union[str,List[str]]]:
296+
def _context_of(self, obj:Object) -> dict[str,str|list[str]]:
297297
context = self._context_without_object()
298298

299-
def set_if_not_none(key:str, val:Union[str,List[str]]) -> None:
299+
def set_if_not_none(key, val) -> None:
300300
if val is not None:
301301
context[key] = val
302302
set_if_not_none(self.NAME_KEY, self.name_of(obj))
@@ -308,7 +308,7 @@ def set_if_not_none(key:str, val:Union[str,List[str]]) -> None:
308308
return context
309309

310310

311-
def render_description(self, obj:Object) -> List[str]:
311+
def render_description(self, obj:Object) -> list[str]:
312312
assert obj
313313
tmpl = TemplateEnvironment().from_string(self.description_template)
314314
description = tmpl.render(self._context_of(obj))

0 commit comments

Comments
 (0)