diff options
| author | Adam Turner <9087854+aa-turner@users.noreply.github.com> | 2022-12-30 21:13:29 +0000 |
|---|---|---|
| committer | Adam Turner <9087854+aa-turner@users.noreply.github.com> | 2023-01-01 20:48:38 +0000 |
| commit | 26f79b0d2dd88b353ac65623897bdfbe8bc07cab (patch) | |
| tree | 0d2f0c752cf1f49a45cde1d7f414d75a6114f1ce /sphinx/pycode | |
| parent | f4c8a0a68e0013808d169357c9f77ebdf19d0f4e (diff) | |
| download | sphinx-git-26f79b0d2dd88b353ac65623897bdfbe8bc07cab.tar.gz | |
Use PEP 595 types
Diffstat (limited to 'sphinx/pycode')
| -rw-r--r-- | sphinx/pycode/__init__.py | 22 | ||||
| -rw-r--r-- | sphinx/pycode/ast.py | 10 | ||||
| -rw-r--r-- | sphinx/pycode/parser.py | 62 |
3 files changed, 47 insertions, 47 deletions
diff --git a/sphinx/pycode/__init__.py b/sphinx/pycode/__init__.py index 68dbab23e..8cba37bb0 100644 --- a/sphinx/pycode/__init__.py +++ b/sphinx/pycode/__init__.py @@ -8,7 +8,7 @@ from collections import OrderedDict from importlib import import_module from inspect import Signature from os import path -from typing import Any, Dict, List, Optional, Tuple +from typing import Any, Optional from zipfile import ZipFile from sphinx.errors import PycodeError @@ -16,18 +16,18 @@ from sphinx.pycode.parser import Parser class ModuleAnalyzer: - annotations: Dict[Tuple[str, str], str] - attr_docs: Dict[Tuple[str, str], List[str]] - finals: List[str] - overloads: Dict[str, List[Signature]] - tagorder: Dict[str, int] - tags: Dict[str, Tuple[str, int, int]] + annotations: dict[tuple[str, str], str] + attr_docs: dict[tuple[str, str], list[str]] + finals: list[str] + overloads: dict[str, list[Signature]] + tagorder: dict[str, int] + tags: dict[str, tuple[str, int, int]] # cache for analyzer objects -- caches both by module and file name - cache: Dict[Tuple[str, str], Any] = {} + cache: dict[tuple[str, str], Any] = {} @staticmethod - def get_module_source(modname: str) -> Tuple[Optional[str], Optional[str]]: + def get_module_source(modname: str) -> tuple[Optional[str], Optional[str]]: """Try to find the source code for a module. Returns ('filename', 'source'). One of it can be None if @@ -160,12 +160,12 @@ class ModuleAnalyzer: except Exception as exc: raise PycodeError('parsing %r failed: %r' % (self.srcname, exc)) from exc - def find_attr_docs(self) -> Dict[Tuple[str, str], List[str]]: + def find_attr_docs(self) -> dict[tuple[str, str], list[str]]: """Find class and module-level attributes and their documentation.""" self.analyze() return self.attr_docs - def find_tags(self) -> Dict[str, Tuple[str, int, int]]: + def find_tags(self) -> dict[str, tuple[str, int, int]]: """Find class, function and method definitions and their location.""" self.analyze() return self.tags diff --git a/sphinx/pycode/ast.py b/sphinx/pycode/ast.py index f5ce196ab..1e773223e 100644 --- a/sphinx/pycode/ast.py +++ b/sphinx/pycode/ast.py @@ -4,11 +4,11 @@ from __future__ import annotations import ast import warnings -from typing import Dict, List, Optional, Type, overload +from typing import Optional, overload from sphinx.deprecation import RemovedInSphinx70Warning -OPERATORS: Dict[Type[ast.AST], str] = { +OPERATORS: dict[type[ast.AST], str] = { ast.Add: "+", ast.And: "and", ast.BitAnd: "&", @@ -91,18 +91,18 @@ class _UnparseVisitor(ast.NodeVisitor): return name def visit_arguments(self, node: ast.arguments) -> str: - defaults: List[Optional[ast.expr]] = list(node.defaults) + defaults: list[Optional[ast.expr]] = list(node.defaults) positionals = len(node.args) posonlyargs = len(node.posonlyargs) positionals += posonlyargs for _ in range(len(defaults), positionals): defaults.insert(0, None) - kw_defaults: List[Optional[ast.expr]] = list(node.kw_defaults) + kw_defaults: list[Optional[ast.expr]] = list(node.kw_defaults) for _ in range(len(kw_defaults), len(node.kwonlyargs)): kw_defaults.insert(0, None) - args: List[str] = [] + args: list[str] = [] for i, arg in enumerate(node.posonlyargs): args.append(self._visit_arg_with_default(arg, defaults[i])) diff --git a/sphinx/pycode/parser.py b/sphinx/pycode/parser.py index cf2303fa9..d13191611 100644 --- a/sphinx/pycode/parser.py +++ b/sphinx/pycode/parser.py @@ -11,7 +11,7 @@ from collections import OrderedDict from inspect import Signature from token import DEDENT, INDENT, NAME, NEWLINE, NUMBER, OP, STRING from tokenize import COMMENT, NL -from typing import Any, Dict, List, Optional, Tuple +from typing import Any, Optional from sphinx.pycode.ast import unparse as ast_unparse @@ -24,7 +24,7 @@ def filter_whitespace(code: str) -> str: return code.replace('\f', ' ') # replace FF (form feed) with whitespace -def get_assign_targets(node: ast.AST) -> List[ast.expr]: +def get_assign_targets(node: ast.AST) -> list[ast.expr]: """Get list of targets from Assign and AnnAssign node.""" if isinstance(node, ast.Assign): return node.targets @@ -32,7 +32,7 @@ def get_assign_targets(node: ast.AST) -> List[ast.expr]: return [node.target] # type: ignore -def get_lvar_names(node: ast.AST, self: Optional[ast.arg] = None) -> List[str]: +def get_lvar_names(node: ast.AST, self: Optional[ast.arg] = None) -> list[str]: """Convert assignment-AST to variable names. This raises `TypeError` if the assignment does not create new variable:: @@ -94,7 +94,7 @@ def dedent_docstring(s: str) -> str: class Token: """Better token wrapper for tokenize module.""" - def __init__(self, kind: int, value: Any, start: Tuple[int, int], end: Tuple[int, int], + def __init__(self, kind: int, value: Any, start: tuple[int, int], end: tuple[int, int], source: str) -> None: self.kind = kind self.value = value @@ -123,7 +123,7 @@ class Token: class TokenProcessor: - def __init__(self, buffers: List[str]) -> None: + def __init__(self, buffers: list[str]) -> None: lines = iter(buffers) self.buffers = buffers self.tokens = tokenize.generate_tokens(lambda: next(lines)) @@ -147,7 +147,7 @@ class TokenProcessor: return self.current - def fetch_until(self, condition: Any) -> List[Token]: + def fetch_until(self, condition: Any) -> list[Token]: """Fetch tokens until specified token appeared. .. note:: This also handles parenthesis well. @@ -174,11 +174,11 @@ class AfterCommentParser(TokenProcessor): and returns the comment for the variable if one exists. """ - def __init__(self, lines: List[str]) -> None: + def __init__(self, lines: list[str]) -> None: super().__init__(lines) self.comment: Optional[str] = None - def fetch_rvalue(self) -> List[Token]: + def fetch_rvalue(self) -> list[Token]: """Fetch right-hand value of assignment.""" tokens = [] while self.fetch_token(): @@ -215,25 +215,25 @@ class AfterCommentParser(TokenProcessor): class VariableCommentPicker(ast.NodeVisitor): """Python source code parser to pick up variable comments.""" - def __init__(self, buffers: List[str], encoding: str) -> None: + def __init__(self, buffers: list[str], encoding: str) -> None: self.counter = itertools.count() self.buffers = buffers self.encoding = encoding - self.context: List[str] = [] - self.current_classes: List[str] = [] + self.context: list[str] = [] + self.current_classes: list[str] = [] self.current_function: Optional[ast.FunctionDef] = None - self.comments: Dict[Tuple[str, str], str] = OrderedDict() - self.annotations: Dict[Tuple[str, str], str] = {} + self.comments: dict[tuple[str, str], str] = OrderedDict() + self.annotations: dict[tuple[str, str], str] = {} self.previous: Optional[ast.AST] = None - self.deforders: Dict[str, int] = {} - self.finals: List[str] = [] - self.overloads: Dict[str, List[Signature]] = {} + self.deforders: dict[str, int] = {} + self.finals: list[str] = [] + self.overloads: dict[str, list[Signature]] = {} self.typing: Optional[str] = None self.typing_final: Optional[str] = None self.typing_overload: Optional[str] = None super().__init__() - def get_qualname_for(self, name: str) -> Optional[List[str]]: + def get_qualname_for(self, name: str) -> Optional[list[str]]: """Get qualified name for given object as a list of string(s).""" if self.current_function: if self.current_classes and self.context[-1] == "__init__": @@ -274,7 +274,7 @@ class VariableCommentPicker(ast.NodeVisitor): basename = ".".join(qualname[:-1]) self.annotations[(basename, name)] = ast_unparse(annotation) - def is_final(self, decorators: List[ast.expr]) -> bool: + def is_final(self, decorators: list[ast.expr]) -> bool: final = [] if self.typing: final.append('%s.final' % self.typing) @@ -290,7 +290,7 @@ class VariableCommentPicker(ast.NodeVisitor): return False - def is_overload(self, decorators: List[ast.expr]) -> bool: + def is_overload(self, decorators: list[ast.expr]) -> bool: overload = [] if self.typing: overload.append('%s.overload' % self.typing) @@ -349,7 +349,7 @@ class VariableCommentPicker(ast.NodeVisitor): """Handles Assign node and pick up a variable comment.""" try: targets = get_assign_targets(node) - varnames: List[str] = sum( + varnames: list[str] = sum( [get_lvar_names(t, self=self.get_self()) for t in targets], [] ) current_line = self.get_line(node.lineno) @@ -465,14 +465,14 @@ class DefinitionFinder(TokenProcessor): classes and methods. """ - def __init__(self, lines: List[str]) -> None: + def __init__(self, lines: list[str]) -> None: super().__init__(lines) self.decorator: Optional[Token] = None - self.context: List[str] = [] - self.indents: List[Tuple[str, Optional[str], Optional[int]]] = [] - self.definitions: Dict[str, Tuple[str, int, int]] = {} + self.context: list[str] = [] + self.indents: list[tuple[str, Optional[str], Optional[int]]] = [] + self.definitions: dict[str, tuple[str, int, int]] = {} - def add_definition(self, name: str, entry: Tuple[str, int, int]) -> None: + def add_definition(self, name: str, entry: tuple[str, int, int]) -> None: """Add a location of definition.""" if self.indents and self.indents[-1][0] == 'def' and entry[0] == 'def': # ignore definition of inner function @@ -544,12 +544,12 @@ class Parser: def __init__(self, code: str, encoding: str = 'utf-8') -> None: self.code = filter_whitespace(code) self.encoding = encoding - self.annotations: Dict[Tuple[str, str], str] = {} - self.comments: Dict[Tuple[str, str], str] = {} - self.deforders: Dict[str, int] = {} - self.definitions: Dict[str, Tuple[str, int, int]] = {} - self.finals: List[str] = [] - self.overloads: Dict[str, List[Signature]] = {} + self.annotations: dict[tuple[str, str], str] = {} + self.comments: dict[tuple[str, str], str] = {} + self.deforders: dict[str, int] = {} + self.definitions: dict[str, tuple[str, int, int]] = {} + self.finals: list[str] = [] + self.overloads: dict[str, list[Signature]] = {} def parse(self) -> None: """Parse the source code.""" |
