From 21d5832ba6db051b9754f515f1d7125126dd801f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Timoth=C3=A9e=20Mazzucotelli?= Date: Sat, 15 Jul 2023 12:22:08 +0200 Subject: [PATCH] refactor: Simplify AST imports, stop using deprecated code from `ast` Issue #179: https://github.com/mkdocstrings/griffe/issues/179 --- src/griffe/agents/nodes/_all.py | 41 ++-- src/griffe/agents/nodes/_docstrings.py | 16 +- src/griffe/agents/nodes/_expressions.py | 314 ++++++++++-------------- src/griffe/agents/nodes/_names.py | 28 +-- src/griffe/agents/nodes/_values.py | 312 +++++++++-------------- src/griffe/finder.py | 2 +- 6 files changed, 279 insertions(+), 434 deletions(-) diff --git a/src/griffe/agents/nodes/_all.py b/src/griffe/agents/nodes/_all.py index 7956f04c..8fd56a15 100644 --- a/src/griffe/agents/nodes/_all.py +++ b/src/griffe/agents/nodes/_all.py @@ -2,16 +2,7 @@ from __future__ import annotations -from ast import AST -from ast import Assign as NodeAssign -from ast import AugAssign as NodeAugAssign -from ast import BinOp as NodeBinOp -from ast import Constant as NodeConstant -from ast import List as NodeList -from ast import Name as NodeName -from ast import Set as NodeSet -from ast import Starred as NodeStarred -from ast import Tuple as NodeTuple +import ast from contextlib import suppress from functools import partial from typing import TYPE_CHECKING, Any, Callable @@ -27,47 +18,47 @@ logger = get_logger(__name__) -def _extract_constant(node: NodeConstant, parent: Module) -> list[str | Name]: +def _extract_constant(node: ast.Constant, parent: Module) -> list[str | Name]: return [node.value] -def _extract_name(node: NodeName, parent: Module) -> list[str | Name]: +def _extract_name(node: ast.Name, parent: Module) -> list[str | Name]: return [Name(node.id, partial(parent.resolve, node.id))] -def _extract_starred(node: NodeStarred, parent: Module) -> list[str | Name]: +def _extract_starred(node: ast.Starred, parent: Module) -> list[str | Name]: return _extract(node.value, parent) -def _extract_sequence(node: NodeList | NodeSet | NodeTuple, parent: Module) -> list[str | Name]: +def _extract_sequence(node: ast.List | ast.Set | ast.Tuple, parent: Module) -> list[str | Name]: sequence = [] for elt in node.elts: sequence.extend(_extract(elt, parent)) return sequence -def _extract_binop(node: NodeBinOp, parent: Module) -> list[str | Name]: +def _extract_binop(node: ast.BinOp, parent: Module) -> list[str | Name]: left = _extract(node.left, parent) right = _extract(node.right, parent) return left + right _node_map: dict[type, Callable[[Any, Module], list[str | Name]]] = { - NodeConstant: _extract_constant, - NodeName: _extract_name, - NodeStarred: _extract_starred, - NodeList: _extract_sequence, - NodeSet: _extract_sequence, - NodeTuple: _extract_sequence, - NodeBinOp: _extract_binop, + ast.Constant: _extract_constant, + ast.Name: _extract_name, + ast.Starred: _extract_starred, + ast.List: _extract_sequence, + ast.Set: _extract_sequence, + ast.Tuple: _extract_sequence, + ast.BinOp: _extract_binop, } -def _extract(node: AST, parent: Module) -> list[str | Name]: +def _extract(node: ast.AST, parent: Module) -> list[str | Name]: return _node_map[type(node)](node, parent) -def get__all__(node: NodeAssign | NodeAugAssign, parent: Module) -> list[str | Name]: +def get__all__(node: ast.Assign | ast.AugAssign, parent: Module) -> list[str | Name]: """Get the values declared in `__all__`. Parameters: @@ -83,7 +74,7 @@ def get__all__(node: NodeAssign | NodeAugAssign, parent: Module) -> list[str | N def safe_get__all__( - node: NodeAssign | NodeAugAssign, + node: ast.Assign | ast.AugAssign, parent: Module, log_level: LogLevel = LogLevel.debug, # TODO: set to error when we handle more things ) -> list[str | Name]: diff --git a/src/griffe/agents/nodes/_docstrings.py b/src/griffe/agents/nodes/_docstrings.py index f6356220..23ec1018 100644 --- a/src/griffe/agents/nodes/_docstrings.py +++ b/src/griffe/agents/nodes/_docstrings.py @@ -2,10 +2,7 @@ from __future__ import annotations -from ast import AST -from ast import Constant as NodeConstant -from ast import Expr as NodeExpr -from ast import Str as NodeStr +import ast from griffe.logger import get_logger @@ -13,7 +10,7 @@ def get_docstring( - node: AST, + node: ast.AST, *, strict: bool = False, ) -> tuple[str | None, int | None, int | None]: @@ -27,17 +24,14 @@ def get_docstring( A tuple with the value and line numbers of the docstring. """ # TODO: possible optimization using a type map - if isinstance(node, NodeExpr): + if isinstance(node, ast.Expr): doc = node.value - elif node.body and isinstance(node.body[0], NodeExpr) and not strict: # type: ignore[attr-defined] + elif node.body and isinstance(node.body[0], ast.Expr) and not strict: # type: ignore[attr-defined] doc = node.body[0].value # type: ignore[attr-defined] else: return None, None, None - if isinstance(doc, NodeConstant) and isinstance(doc.value, str): + if isinstance(doc, ast.Constant) and isinstance(doc.value, str): return doc.value, doc.lineno, doc.end_lineno - if isinstance(doc, NodeStr): - lineno = doc.lineno - return doc.s, lineno, doc.end_lineno return None, None, None diff --git a/src/griffe/agents/nodes/_expressions.py b/src/griffe/agents/nodes/_expressions.py index 7322818d..a7c971e0 100644 --- a/src/griffe/agents/nodes/_expressions.py +++ b/src/griffe/agents/nodes/_expressions.py @@ -2,77 +2,14 @@ from __future__ import annotations +import ast import sys -from ast import AST, PyCF_ONLY_AST -from ast import Add as NodeAdd -from ast import And as NodeAnd -from ast import Attribute as NodeAttribute -from ast import BinOp as NodeBinOp -from ast import BitAnd as NodeBitAnd -from ast import BitOr as NodeBitOr -from ast import BitXor as NodeBitXor -from ast import BoolOp as NodeBoolOp -from ast import Call as NodeCall -from ast import Compare as NodeCompare -from ast import Constant as NodeConstant -from ast import Dict as NodeDict -from ast import DictComp as NodeDictComp -from ast import Div as NodeDiv -from ast import Ellipsis as NodeEllipsis -from ast import Eq as NodeEq -from ast import FloorDiv as NodeFloorDiv -from ast import FormattedValue as NodeFormattedValue -from ast import GeneratorExp as NodeGeneratorExp -from ast import Gt as NodeGt -from ast import GtE as NodeGtE -from ast import IfExp as NodeIfExp -from ast import In as NodeIn -from ast import Invert as NodeInvert -from ast import Is as NodeIs -from ast import IsNot as NodeIsNot -from ast import JoinedStr as NodeJoinedStr -from ast import Lambda as NodeLambda -from ast import List as NodeList -from ast import ListComp as NodeListComp -from ast import LShift as NodeLShift -from ast import Lt as NodeLt -from ast import LtE as NodeLtE -from ast import MatMult as NodeMatMult -from ast import Mod as NodeMod -from ast import Mult as NodeMult -from ast import Name as NodeName -from ast import NamedExpr as NodeNamedExpr -from ast import Not as NodeNot -from ast import NotEq as NodeNotEq -from ast import NotIn as NodeNotIn -from ast import Or as NodeOr -from ast import Pow as NodePow -from ast import RShift as NodeRShift -from ast import Set as NodeSet -from ast import SetComp as NodeSetComp -from ast import Slice as NodeSlice -from ast import Starred as NodeStarred -from ast import Sub as NodeSub -from ast import Subscript as NodeSubscript -from ast import Tuple as NodeTuple -from ast import UAdd as NodeUAdd -from ast import UnaryOp as NodeUnaryOp -from ast import USub as NodeUSub -from ast import Yield as NodeYield -from ast import arguments as NodeArguments -from ast import comprehension as NodeComprehension -from ast import keyword as NodeKeyword from functools import partial from typing import TYPE_CHECKING, Any, Callable, Sequence from griffe.expressions import Expression, Name from griffe.logger import LogLevel, get_logger -# TODO: remove once Python 3.8 support is dropped -if sys.version_info < (3, 9): - from ast import ExtSlice as NodeExtSlice - from ast import Index as NodeIndex - if TYPE_CHECKING: from pathlib import Path @@ -92,19 +29,19 @@ def _join(sequence: Sequence, item: str | Name | Expression) -> list: return new_sequence -def _build_add(node: NodeAdd, parent: Module | Class, **kwargs: Any) -> str: +def _build_add(node: ast.Add, parent: Module | Class, **kwargs: Any) -> str: return "+" -def _build_and(node: NodeAnd, parent: Module | Class, **kwargs: Any) -> str: +def _build_and(node: ast.And, parent: Module | Class, **kwargs: Any) -> str: return "and" -def _build_arguments(node: NodeArguments, parent: Module | Class, **kwargs: Any) -> str: +def _build_arguments(node: ast.arguments, parent: Module | Class, **kwargs: Any) -> str: return ", ".join(arg.arg for arg in node.args) -def _build_attribute(node: NodeAttribute, parent: Module | Class, **kwargs: Any) -> Expression: +def _build_attribute(node: ast.Attribute, parent: Module | Class, **kwargs: Any) -> Expression: left = _build(node.value, parent, **kwargs) if isinstance(left, str): @@ -118,31 +55,31 @@ def resolver() -> str: # type: ignore[misc] return Expression(left, ".", right) -def _build_binop(node: NodeBinOp, parent: Module | Class, **kwargs: Any) -> Expression: +def _build_binop(node: ast.BinOp, parent: Module | Class, **kwargs: Any) -> Expression: left = _build(node.left, parent, **kwargs) right = _build(node.right, parent, **kwargs) return Expression(left, " ", _build(node.op, parent, **kwargs), " ", right) -def _build_bitand(node: NodeBitAnd, parent: Module | Class, **kwargs: Any) -> str: +def _build_bitand(node: ast.BitAnd, parent: Module | Class, **kwargs: Any) -> str: return "&" -def _build_bitor(node: NodeBitOr, parent: Module | Class, **kwargs: Any) -> str: +def _build_bitor(node: ast.BitOr, parent: Module | Class, **kwargs: Any) -> str: return "|" -def _build_bitxor(node: NodeBitXor, parent: Module | Class, **kwargs: Any) -> str: +def _build_bitxor(node: ast.BitXor, parent: Module | Class, **kwargs: Any) -> str: return "^" -def _build_boolop(node: NodeBoolOp, parent: Module | Class, **kwargs: Any) -> Expression: +def _build_boolop(node: ast.BoolOp, parent: Module | Class, **kwargs: Any) -> Expression: return Expression( *_join([_build(value, parent, **kwargs) for value in node.values], f" {_build(node.op, parent, **kwargs)} "), ) -def _build_call(node: NodeCall, parent: Module | Class, **kwargs: Any) -> Expression: +def _build_call(node: ast.Call, parent: Module | Class, **kwargs: Any) -> Expression: positional_args = Expression(*_join([_build(arg, parent, **kwargs) for arg in node.args], ", ")) keyword_args = Expression(*_join([_build(kwarg, parent, **kwargs) for kwarg in node.keywords], ", ")) args: Expression | str @@ -157,14 +94,14 @@ def _build_call(node: NodeCall, parent: Module | Class, **kwargs: Any) -> Expres return Expression(_build(node.func, parent, **kwargs), "(", args, ")") -def _build_compare(node: NodeCompare, parent: Module | Class, **kwargs: Any) -> Expression: +def _build_compare(node: ast.Compare, parent: Module | Class, **kwargs: Any) -> Expression: left = _build(node.left, parent, **kwargs) ops = [_build(op, parent, **kwargs) for op in node.ops] comparators = [_build(comparator, parent, **kwargs) for comparator in node.comparators] return Expression(left, " ", *_join([Expression(op, " ", comp) for op, comp in zip(ops, comparators)], " ")) -def _build_comprehension(node: NodeComprehension, parent: Module | Class, **kwargs: Any) -> Expression: +def _build_comprehension(node: ast.comprehension, parent: Module | Class, **kwargs: Any) -> Expression: target = _build(node.target, parent, **kwargs) iterable = _build(node.iter, parent, **kwargs) conditions = [_build(condition, parent, **kwargs) for condition in node.ifs] @@ -177,7 +114,7 @@ def _build_comprehension(node: NodeComprehension, parent: Module | Class, **kwar def _build_constant( - node: NodeConstant, + node: ast.Constant, parent: Module | Class, *, in_formatted_str: bool = False, @@ -200,7 +137,7 @@ def _build_constant( node.value, mode="eval", filename="", - flags=PyCF_ONLY_AST, + flags=ast.PyCF_ONLY_AST, optimize=1, ) except SyntaxError: @@ -214,7 +151,7 @@ def _build_constant( return {type(...): lambda _: "..."}.get(type(node.value), repr)(node.value) -def _build_dict(node: NodeDict, parent: Module | Class, **kwargs: Any) -> Expression: +def _build_dict(node: ast.Dict, parent: Module | Class, **kwargs: Any) -> Expression: pairs = zip(node.keys, node.values) body = [ Expression("None" if key is None else _build(key, parent, **kwargs), ": ", _build(value, parent, **kwargs)) @@ -223,48 +160,44 @@ def _build_dict(node: NodeDict, parent: Module | Class, **kwargs: Any) -> Expres return Expression("{", Expression(*_join(body, ", ")), "}") -def _build_dictcomp(node: NodeDictComp, parent: Module | Class, **kwargs: Any) -> Expression: +def _build_dictcomp(node: ast.DictComp, parent: Module | Class, **kwargs: Any) -> Expression: key = _build(node.key, parent, **kwargs) value = _build(node.value, parent, **kwargs) generators = [_build(gen, parent, **kwargs) for gen in node.generators] return Expression("{", key, ": ", value, Expression(*_join(generators, " ")), "}") -def _build_div(node: NodeDiv, parent: Module | Class, **kwargs: Any) -> str: +def _build_div(node: ast.Div, parent: Module | Class, **kwargs: Any) -> str: return "/" -def _build_ellipsis(node: NodeEllipsis, parent: Module | Class, **kwargs: Any) -> str: - return "..." - - -def _build_eq(node: NodeEq, parent: Module | Class, **kwargs: Any) -> str: +def _build_eq(node: ast.Eq, parent: Module | Class, **kwargs: Any) -> str: return "==" -def _build_floordiv(node: NodeFloorDiv, parent: Module | Class, **kwargs: Any) -> str: +def _build_floordiv(node: ast.FloorDiv, parent: Module | Class, **kwargs: Any) -> str: return "//" -def _build_formatted(node: NodeFormattedValue, parent: Module | Class, **kwargs: Any) -> Expression: +def _build_formatted(node: ast.FormattedValue, parent: Module | Class, **kwargs: Any) -> Expression: return Expression("{", _build(node.value, parent, in_formatted_str=True, **kwargs), "}") -def _build_generatorexp(node: NodeGeneratorExp, parent: Module | Class, **kwargs: Any) -> Expression: +def _build_generatorexp(node: ast.GeneratorExp, parent: Module | Class, **kwargs: Any) -> Expression: element = _build(node.elt, parent, **kwargs) generators = [_build(gen, parent, **kwargs) for gen in node.generators] return Expression(element, " ", Expression(*_join(generators, " "))) -def _build_gte(node: NodeGtE, parent: Module | Class, **kwargs: Any) -> str: +def _build_gte(node: ast.GtE, parent: Module | Class, **kwargs: Any) -> str: return ">=" -def _build_gt(node: NodeGt, parent: Module | Class, **kwargs: Any) -> str: +def _build_gt(node: ast.Gt, parent: Module | Class, **kwargs: Any) -> str: return ">" -def _build_ifexp(node: NodeIfExp, parent: Module | Class, **kwargs: Any) -> Expression: +def _build_ifexp(node: ast.IfExp, parent: Module | Class, **kwargs: Any) -> Expression: return Expression( _build(node.body, parent, **kwargs), " if ", @@ -274,113 +207,113 @@ def _build_ifexp(node: NodeIfExp, parent: Module | Class, **kwargs: Any) -> Expr ) -def _build_invert(node: NodeInvert, parent: Module | Class, **kwargs: Any) -> str: +def _build_invert(node: ast.Invert, parent: Module | Class, **kwargs: Any) -> str: return "~" -def _build_in(node: NodeIn, parent: Module | Class, **kwargs: Any) -> str: +def _build_in(node: ast.In, parent: Module | Class, **kwargs: Any) -> str: return "in" -def _build_is(node: NodeIs, parent: Module | Class, **kwargs: Any) -> str: +def _build_is(node: ast.Is, parent: Module | Class, **kwargs: Any) -> str: return "is" -def _build_isnot(node: NodeIsNot, parent: Module | Class, **kwargs: Any) -> str: +def _build_isnot(node: ast.IsNot, parent: Module | Class, **kwargs: Any) -> str: return "is not" -def _build_joinedstr(node: NodeJoinedStr, parent: Module | Class, **kwargs: Any) -> Expression: +def _build_joinedstr(node: ast.JoinedStr, parent: Module | Class, **kwargs: Any) -> Expression: return Expression("f'", *[_build(value, parent, in_joined_str=True) for value in node.values], "'") -def _build_keyword(node: NodeKeyword, parent: Module | Class, **kwargs: Any) -> Expression: +def _build_keyword(node: ast.keyword, parent: Module | Class, **kwargs: Any) -> Expression: if node.arg is None: return Expression("**", _build(node.value, parent, **kwargs)) return Expression(node.arg, "=", _build(node.value, parent, **kwargs)) -def _build_lambda(node: NodeLambda, parent: Module | Class, **kwargs: Any) -> Expression: +def _build_lambda(node: ast.Lambda, parent: Module | Class, **kwargs: Any) -> Expression: return Expression("lambda ", _build(node.args, parent, **kwargs), ": ", _build(node.body, parent, **kwargs)) -def _build_list(node: NodeList, parent: Module | Class, **kwargs: Any) -> Expression: +def _build_list(node: ast.List, parent: Module | Class, **kwargs: Any) -> Expression: return Expression("[", *_join([_build(el, parent, **kwargs) for el in node.elts], ", "), "]") -def _build_listcomp(node: NodeListComp, parent: Module | Class, **kwargs: Any) -> Expression: +def _build_listcomp(node: ast.ListComp, parent: Module | Class, **kwargs: Any) -> Expression: element = _build(node.elt, parent, **kwargs) generators = [_build(gen, parent, **kwargs) for gen in node.generators] return Expression("[", element, *_join(generators, " "), "]") -def _build_lshift(node: NodeLShift, parent: Module | Class, **kwargs: Any) -> str: +def _build_lshift(node: ast.LShift, parent: Module | Class, **kwargs: Any) -> str: return "<<" -def _build_lte(node: NodeLtE, parent: Module | Class, **kwargs: Any) -> str: +def _build_lte(node: ast.LtE, parent: Module | Class, **kwargs: Any) -> str: return "<=" -def _build_lt(node: NodeLt, parent: Module | Class, **kwargs: Any) -> str: +def _build_lt(node: ast.Lt, parent: Module | Class, **kwargs: Any) -> str: return "<" -def _build_matmult(node: NodeMatMult, parent: Module | Class, **kwargs: Any) -> str: +def _build_matmult(node: ast.MatMult, parent: Module | Class, **kwargs: Any) -> str: return "@" -def _build_mod(node: NodeMod, parent: Module | Class, **kwargs: Any) -> str: +def _build_mod(node: ast.Mod, parent: Module | Class, **kwargs: Any) -> str: return "%" -def _build_mult(node: NodeMult, parent: Module | Class, **kwargs: Any) -> str: +def _build_mult(node: ast.Mult, parent: Module | Class, **kwargs: Any) -> str: return "*" -def _build_name(node: NodeName, parent: Module | Class, **kwargs: Any) -> Name: +def _build_name(node: ast.Name, parent: Module | Class, **kwargs: Any) -> Name: return Name(node.id, partial(parent.resolve, node.id)) -def _build_named_expr(node: NodeNamedExpr, parent: Module | Class, **kwargs: Any) -> Expression: +def _build_named_expr(node: ast.NamedExpr, parent: Module | Class, **kwargs: Any) -> Expression: return Expression("(", _build(node.target, parent, **kwargs), " := ", _build(node.value, parent, **kwargs), ")") -def _build_not(node: NodeNot, parent: Module | Class, **kwargs: Any) -> str: +def _build_not(node: ast.Not, parent: Module | Class, **kwargs: Any) -> str: return "not " -def _build_noteq(node: NodeNotEq, parent: Module | Class, **kwargs: Any) -> str: +def _build_noteq(node: ast.NotEq, parent: Module | Class, **kwargs: Any) -> str: return "!=" -def _build_notin(node: NodeNotIn, parent: Module | Class, **kwargs: Any) -> str: +def _build_notin(node: ast.NotIn, parent: Module | Class, **kwargs: Any) -> str: return "not in" -def _build_or(node: NodeOr, parent: Module | Class, **kwargs: Any) -> str: +def _build_or(node: ast.Or, parent: Module | Class, **kwargs: Any) -> str: return "or" -def _build_pow(node: NodePow, parent: Module | Class, **kwargs: Any) -> str: +def _build_pow(node: ast.Pow, parent: Module | Class, **kwargs: Any) -> str: return "**" -def _build_rshift(node: NodeRShift, parent: Module | Class, **kwargs: Any) -> str: +def _build_rshift(node: ast.RShift, parent: Module | Class, **kwargs: Any) -> str: return ">>" -def _build_set(node: NodeSet, parent: Module | Class, **kwargs: Any) -> Expression: +def _build_set(node: ast.Set, parent: Module | Class, **kwargs: Any) -> Expression: return Expression("{", *_join([_build(el, parent, **kwargs) for el in node.elts], ", "), "}") -def _build_setcomp(node: NodeSetComp, parent: Module | Class, **kwargs: Any) -> Expression: +def _build_setcomp(node: ast.SetComp, parent: Module | Class, **kwargs: Any) -> Expression: element = _build(node.elt, parent, **kwargs) generators = [_build(gen, parent, **kwargs) for gen in node.generators] return Expression("{", element, " ", *_join(generators, " "), "}") -def _build_slice(node: NodeSlice, parent: Module | Class, **kwargs: Any) -> Expression: +def _build_slice(node: ast.Slice, parent: Module | Class, **kwargs: Any) -> Expression: lower = _build(node.lower, parent, **kwargs) if node.lower else "" upper = _build(node.upper, parent, **kwargs) if node.upper else "" value = Expression(lower, ":", upper) @@ -389,16 +322,16 @@ def _build_slice(node: NodeSlice, parent: Module | Class, **kwargs: Any) -> Expr return value -def _build_starred(node: NodeStarred, parent: Module | Class, **kwargs: Any) -> Expression: +def _build_starred(node: ast.Starred, parent: Module | Class, **kwargs: Any) -> Expression: return Expression("*", _build(node.value, parent, **kwargs)) -def _build_sub(node: NodeSub, parent: Module | Class, **kwargs: Any) -> str: +def _build_sub(node: ast.Sub, parent: Module | Class, **kwargs: Any) -> str: return "-" def _build_subscript( - node: NodeSubscript, + node: ast.Subscript, parent: Module | Class, *, parse_strings: bool = False, @@ -413,108 +346,107 @@ def _build_subscript( return Expression(left, "[", subscript, "]") -def _build_tuple(node: NodeTuple, parent: Module | Class, **kwargs: Any) -> Expression: +def _build_tuple(node: ast.Tuple, parent: Module | Class, **kwargs: Any) -> Expression: return Expression(*_join([_build(el, parent, **kwargs) for el in node.elts], ", ")) -def _build_uadd(node: NodeUAdd, parent: Module | Class, **kwargs: Any) -> str: +def _build_uadd(node: ast.UAdd, parent: Module | Class, **kwargs: Any) -> str: return "+" -def _build_unaryop(node: NodeUnaryOp, parent: Module | Class, **kwargs: Any) -> Expression: +def _build_unaryop(node: ast.UnaryOp, parent: Module | Class, **kwargs: Any) -> Expression: return Expression(_build(node.op, parent, **kwargs), _build(node.operand, parent, **kwargs)) -def _build_usub(node: NodeUSub, parent: Module | Class, **kwargs: Any) -> str: +def _build_usub(node: ast.USub, parent: Module | Class, **kwargs: Any) -> str: return "-" -def _build_yield(node: NodeYield, parent: Module | Class, **kwargs: Any) -> str | Name | Expression: +def _build_yield(node: ast.Yield, parent: Module | Class, **kwargs: Any) -> str | Name | Expression: if node.value is None: return repr(None) return _build(node.value, parent, **kwargs) _node_map: dict[type, Callable[[Any, Module | Class], str | Name | Expression]] = { - NodeAdd: _build_add, - NodeAnd: _build_and, - NodeArguments: _build_arguments, - NodeAttribute: _build_attribute, - NodeBinOp: _build_binop, - NodeBitAnd: _build_bitand, - NodeBitOr: _build_bitor, - NodeBitXor: _build_bitxor, - NodeBoolOp: _build_boolop, - NodeCall: _build_call, - NodeCompare: _build_compare, - NodeComprehension: _build_comprehension, - NodeConstant: _build_constant, - NodeDict: _build_dict, - NodeDictComp: _build_dictcomp, - NodeDiv: _build_div, - NodeEllipsis: _build_ellipsis, - NodeEq: _build_eq, - NodeFloorDiv: _build_floordiv, - NodeFormattedValue: _build_formatted, - NodeGeneratorExp: _build_generatorexp, - NodeGt: _build_gt, - NodeGtE: _build_gte, - NodeIfExp: _build_ifexp, - NodeIn: _build_in, - NodeInvert: _build_invert, - NodeIs: _build_is, - NodeIsNot: _build_isnot, - NodeJoinedStr: _build_joinedstr, - NodeKeyword: _build_keyword, - NodeLambda: _build_lambda, - NodeList: _build_list, - NodeListComp: _build_listcomp, - NodeLShift: _build_lshift, - NodeLt: _build_lt, - NodeLtE: _build_lte, - NodeMatMult: _build_matmult, - NodeMod: _build_mod, - NodeMult: _build_mult, - NodeName: _build_name, - NodeNamedExpr: _build_named_expr, - NodeNot: _build_not, - NodeNotEq: _build_noteq, - NodeNotIn: _build_notin, - NodeOr: _build_or, - NodePow: _build_pow, - NodeRShift: _build_rshift, - NodeSet: _build_set, - NodeSetComp: _build_setcomp, - NodeSlice: _build_slice, - NodeStarred: _build_starred, - NodeSub: _build_sub, - NodeSubscript: _build_subscript, - NodeTuple: _build_tuple, - NodeUAdd: _build_uadd, - NodeUnaryOp: _build_unaryop, - NodeUSub: _build_usub, - NodeYield: _build_yield, + ast.Add: _build_add, + ast.And: _build_and, + ast.arguments: _build_arguments, + ast.Attribute: _build_attribute, + ast.BinOp: _build_binop, + ast.BitAnd: _build_bitand, + ast.BitOr: _build_bitor, + ast.BitXor: _build_bitxor, + ast.BoolOp: _build_boolop, + ast.Call: _build_call, + ast.Compare: _build_compare, + ast.comprehension: _build_comprehension, + ast.Constant: _build_constant, + ast.Dict: _build_dict, + ast.DictComp: _build_dictcomp, + ast.Div: _build_div, + ast.Eq: _build_eq, + ast.FloorDiv: _build_floordiv, + ast.FormattedValue: _build_formatted, + ast.GeneratorExp: _build_generatorexp, + ast.Gt: _build_gt, + ast.GtE: _build_gte, + ast.IfExp: _build_ifexp, + ast.In: _build_in, + ast.Invert: _build_invert, + ast.Is: _build_is, + ast.IsNot: _build_isnot, + ast.JoinedStr: _build_joinedstr, + ast.keyword: _build_keyword, + ast.Lambda: _build_lambda, + ast.List: _build_list, + ast.ListComp: _build_listcomp, + ast.LShift: _build_lshift, + ast.Lt: _build_lt, + ast.LtE: _build_lte, + ast.MatMult: _build_matmult, + ast.Mod: _build_mod, + ast.Mult: _build_mult, + ast.Name: _build_name, + ast.NamedExpr: _build_named_expr, + ast.Not: _build_not, + ast.NotEq: _build_noteq, + ast.NotIn: _build_notin, + ast.Or: _build_or, + ast.Pow: _build_pow, + ast.RShift: _build_rshift, + ast.Set: _build_set, + ast.SetComp: _build_setcomp, + ast.Slice: _build_slice, + ast.Starred: _build_starred, + ast.Sub: _build_sub, + ast.Subscript: _build_subscript, + ast.Tuple: _build_tuple, + ast.UAdd: _build_uadd, + ast.UnaryOp: _build_unaryop, + ast.USub: _build_usub, + ast.Yield: _build_yield, } # TODO: remove once Python 3.8 support is dropped if sys.version_info < (3, 9): - def _build_extslice(node: NodeExtSlice, parent: Module | Class, **kwargs: Any) -> Expression: + def _build_extslice(node: ast.ExtSlice, parent: Module | Class, **kwargs: Any) -> Expression: return Expression(*_join([_build(dim, parent, **kwargs) for dim in node.dims], ",")) - def _build_index(node: NodeIndex, parent: Module | Class, **kwargs: Any) -> str | Name | Expression: + def _build_index(node: ast.Index, parent: Module | Class, **kwargs: Any) -> str | Name | Expression: return _build(node.value, parent, **kwargs) - _node_map[NodeExtSlice] = _build_extslice - _node_map[NodeIndex] = _build_index + _node_map[ast.ExtSlice] = _build_extslice + _node_map[ast.Index] = _build_index -def _build(node: AST, parent: Module | Class, **kwargs: Any) -> str | Name | Expression: +def _build(node: ast.AST, parent: Module | Class, **kwargs: Any) -> str | Name | Expression: return _node_map[type(node)](node, parent, **kwargs) def get_expression( - node: AST | None, + node: ast.AST | None, parent: Module | Class, *, parse_strings: bool | None = None, @@ -542,7 +474,7 @@ def get_expression( def safe_get_expression( - node: AST | None, + node: ast.AST | None, parent: Module | Class, *, parse_strings: bool | None = None, diff --git a/src/griffe/agents/nodes/_names.py b/src/griffe/agents/nodes/_names.py index 85332f46..b3fc5fda 100644 --- a/src/griffe/agents/nodes/_names.py +++ b/src/griffe/agents/nodes/_names.py @@ -2,11 +2,7 @@ from __future__ import annotations -from ast import AST -from ast import AnnAssign as NodeAnnAssign -from ast import Assign as NodeAssign -from ast import Attribute as NodeAttribute -from ast import Name as NodeName +import ast from typing import Any, Callable from griffe.logger import get_logger @@ -14,21 +10,21 @@ logger = get_logger(__name__) -def _get_attribute_name(node: NodeAttribute) -> str: +def _get_attribute_name(node: ast.Attribute) -> str: return f"{get_name(node.value)}.{node.attr}" -def _get_name_name(node: NodeName) -> str: +def _get_name_name(node: ast.Name) -> str: return node.id _node_name_map: dict[type, Callable[[Any], str]] = { - NodeName: _get_name_name, - NodeAttribute: _get_attribute_name, + ast.Name: _get_name_name, + ast.Attribute: _get_attribute_name, } -def get_name(node: AST) -> str: +def get_name(node: ast.AST) -> str: """Extract name from an assignment node. Parameters: @@ -40,23 +36,23 @@ def get_name(node: AST) -> str: return _node_name_map[type(node)](node) -def _get_assign_names(node: NodeAssign) -> list[str]: +def _get_assign_names(node: ast.Assign) -> list[str]: names = (get_name(target) for target in node.targets) return [name for name in names if name] -def _get_annassign_names(node: NodeAnnAssign) -> list[str]: +def _get_annassign_names(node: ast.AnnAssign) -> list[str]: name = get_name(node.target) return [name] if name else [] _node_names_map: dict[type, Callable[[Any], list[str]]] = { - NodeAssign: _get_assign_names, - NodeAnnAssign: _get_annassign_names, + ast.Assign: _get_assign_names, + ast.AnnAssign: _get_annassign_names, } -def get_names(node: AST) -> list[str]: +def get_names(node: ast.AST) -> list[str]: """Extract names from an assignment node. Parameters: @@ -68,7 +64,7 @@ def get_names(node: AST) -> list[str]: return _node_names_map[type(node)](node) -def get_instance_names(node: AST) -> list[str]: +def get_instance_names(node: ast.AST) -> list[str]: """Extract names from an assignment node, only for instance attributes. Parameters: diff --git a/src/griffe/agents/nodes/_values.py b/src/griffe/agents/nodes/_values.py index 2bc1e809..130f5af8 100644 --- a/src/griffe/agents/nodes/_values.py +++ b/src/griffe/agents/nodes/_values.py @@ -2,75 +2,12 @@ from __future__ import annotations +import ast import sys -from ast import AST -from ast import Add as NodeAdd -from ast import And as NodeAnd -from ast import Attribute as NodeAttribute -from ast import BinOp as NodeBinOp -from ast import BitAnd as NodeBitAnd -from ast import BitOr as NodeBitOr -from ast import BitXor as NodeBitXor -from ast import BoolOp as NodeBoolOp -from ast import Call as NodeCall -from ast import Compare as NodeCompare -from ast import Constant as NodeConstant -from ast import Dict as NodeDict -from ast import DictComp as NodeDictComp -from ast import Div as NodeDiv -from ast import Ellipsis as NodeEllipsis -from ast import Eq as NodeEq -from ast import FloorDiv as NodeFloorDiv -from ast import FormattedValue as NodeFormattedValue -from ast import GeneratorExp as NodeGeneratorExp -from ast import Gt as NodeGt -from ast import GtE as NodeGtE -from ast import IfExp as NodeIfExp -from ast import In as NodeIn -from ast import Invert as NodeInvert -from ast import Is as NodeIs -from ast import IsNot as NodeIsNot -from ast import JoinedStr as NodeJoinedStr -from ast import Lambda as NodeLambda -from ast import List as NodeList -from ast import ListComp as NodeListComp -from ast import LShift as NodeLShift -from ast import Lt as NodeLt -from ast import LtE as NodeLtE -from ast import MatMult as NodeMatMult -from ast import Mod as NodeMod -from ast import Mult as NodeMult -from ast import Name as NodeName -from ast import NamedExpr as NodeNamedExpr -from ast import Not as NodeNot -from ast import NotEq as NodeNotEq -from ast import NotIn as NodeNotIn -from ast import Or as NodeOr -from ast import Pow as NodePow -from ast import RShift as NodeRShift -from ast import Set as NodeSet -from ast import SetComp as NodeSetComp -from ast import Slice as NodeSlice -from ast import Starred as NodeStarred -from ast import Sub as NodeSub -from ast import Subscript as NodeSubscript -from ast import Tuple as NodeTuple -from ast import UAdd as NodeUAdd -from ast import UnaryOp as NodeUnaryOp -from ast import USub as NodeUSub -from ast import Yield as NodeYield -from ast import arguments as NodeArguments -from ast import comprehension as NodeComprehension -from ast import keyword as NodeKeyword from typing import TYPE_CHECKING, Any, Callable from griffe.logger import get_logger -# TODO: remove once Python 3.8 support is dropped -if sys.version_info < (3, 9): - from ast import ExtSlice as NodeExtSlice - from ast import Index as NodeIndex - if TYPE_CHECKING: from pathlib import Path @@ -78,43 +15,43 @@ logger = get_logger(__name__) -def _extract_add(node: NodeAdd, **kwargs: Any) -> str: +def _extract_add(node: ast.Add, **kwargs: Any) -> str: return "+" -def _extract_and(node: NodeAnd, **kwargs: Any) -> str: +def _extract_and(node: ast.And, **kwargs: Any) -> str: return "and" -def _extract_arguments(node: NodeArguments, **kwargs: Any) -> str: +def _extract_arguments(node: ast.arguments, **kwargs: Any) -> str: return ", ".join(arg.arg for arg in node.args) -def _extract_attribute(node: NodeAttribute, **kwargs: Any) -> str: +def _extract_attribute(node: ast.Attribute, **kwargs: Any) -> str: return f"{_extract(node.value, **kwargs)}.{node.attr}" -def _extract_binop(node: NodeBinOp, **kwargs: Any) -> str: +def _extract_binop(node: ast.BinOp, **kwargs: Any) -> str: return f"{_extract(node.left, **kwargs)} {_extract(node.op, **kwargs)} {_extract(node.right, **kwargs)}" -def _extract_bitor(node: NodeBitOr, **kwargs: Any) -> str: +def _extract_bitor(node: ast.BitOr, **kwargs: Any) -> str: return "|" -def _extract_bitand(node: NodeBitAnd, **kwargs: Any) -> str: +def _extract_bitand(node: ast.BitAnd, **kwargs: Any) -> str: return "&" -def _extract_bitxor(node: NodeBitXor, **kwargs: Any) -> str: +def _extract_bitxor(node: ast.BitXor, **kwargs: Any) -> str: return "^" -def _extract_boolop(node: NodeBoolOp, **kwargs: Any) -> str: +def _extract_boolop(node: ast.BoolOp, **kwargs: Any) -> str: return f" {_extract(node.op, **kwargs)} ".join(_extract(value, **kwargs) for value in node.values) -def _extract_call(node: NodeCall, **kwargs: Any) -> str: +def _extract_call(node: ast.Call, **kwargs: Any) -> str: positional_args = ", ".join(_extract(arg, **kwargs) for arg in node.args) keyword_args = ", ".join(_extract(kwarg, **kwargs) for kwarg in node.keywords) if positional_args and keyword_args: @@ -128,14 +65,14 @@ def _extract_call(node: NodeCall, **kwargs: Any) -> str: return f"{_extract(node.func, **kwargs)}({args})" -def _extract_compare(node: NodeCompare, **kwargs: Any) -> str: +def _extract_compare(node: ast.Compare, **kwargs: Any) -> str: left = _extract(node.left, **kwargs) ops = [_extract(op, **kwargs) for op in node.ops] comparators = [_extract(comparator, **kwargs) for comparator in node.comparators] return f"{left} " + " ".join(f"{op} {comp}" for op, comp in zip(ops, comparators)) -def _extract_comprehension(node: NodeComprehension, **kwargs: Any) -> str: +def _extract_comprehension(node: ast.comprehension, **kwargs: Any) -> str: target = _extract(node.target, **kwargs) iterable = _extract(node.iter, **kwargs) conditions = [_extract(condition, **kwargs) for condition in node.ifs] @@ -148,7 +85,7 @@ def _extract_comprehension(node: NodeComprehension, **kwargs: Any) -> str: def _extract_constant( - node: NodeConstant, + node: ast.Constant, *, in_formatted_str: bool = False, in_joined_str: bool = False, @@ -159,164 +96,160 @@ def _extract_constant( return {type(...): lambda _: "..."}.get(type(node.value), repr)(node.value) -def _extract_dict(node: NodeDict, **kwargs: Any) -> str: +def _extract_dict(node: ast.Dict, **kwargs: Any) -> str: pairs = zip(node.keys, node.values) gen = (f"{'None' if key is None else _extract(key, **kwargs)}: {_extract(value, **kwargs)}" for key, value in pairs) return "{" + ", ".join(gen) + "}" -def _extract_dictcomp(node: NodeDictComp, **kwargs: Any) -> str: +def _extract_dictcomp(node: ast.DictComp, **kwargs: Any) -> str: key = _extract(node.key, **kwargs) value = _extract(node.value, **kwargs) generators = [_extract(gen, **kwargs) for gen in node.generators] return f"{{{key}: {value} " + " ".join(generators) + "}" -def _extract_div(node: NodeDiv, **kwargs: Any) -> str: +def _extract_div(node: ast.Div, **kwargs: Any) -> str: return "/" -def _extract_ellipsis(node: NodeEllipsis, **kwargs: Any) -> str: - return "..." - - -def _extract_eq(node: NodeEq, **kwargs: Any) -> str: +def _extract_eq(node: ast.Eq, **kwargs: Any) -> str: return "==" -def _extract_floordiv(node: NodeFloorDiv, **kwargs: Any) -> str: +def _extract_floordiv(node: ast.FloorDiv, **kwargs: Any) -> str: return "//" -def _extract_formatted(node: NodeFormattedValue, **kwargs: Any) -> str: +def _extract_formatted(node: ast.FormattedValue, **kwargs: Any) -> str: return f"{{{_extract(node.value, in_formatted_str=True, **kwargs)}}}" -def _extract_generatorexp(node: NodeGeneratorExp, **kwargs: Any) -> str: +def _extract_generatorexp(node: ast.GeneratorExp, **kwargs: Any) -> str: element = _extract(node.elt, **kwargs) generators = [_extract(gen, **kwargs) for gen in node.generators] return f"{element} " + " ".join(generators) -def _extract_gte(node: NodeNotEq, **kwargs: Any) -> str: +def _extract_gte(node: ast.NotEq, **kwargs: Any) -> str: return ">=" -def _extract_gt(node: NodeNotEq, **kwargs: Any) -> str: +def _extract_gt(node: ast.NotEq, **kwargs: Any) -> str: return ">" -def _extract_ifexp(node: NodeIfExp, **kwargs: Any) -> str: +def _extract_ifexp(node: ast.IfExp, **kwargs: Any) -> str: return f"{_extract(node.body, **kwargs)} if {_extract(node.test, **kwargs)} else {_extract(node.orelse, **kwargs)}" -def _extract_invert(node: NodeInvert, **kwargs: Any) -> str: +def _extract_invert(node: ast.Invert, **kwargs: Any) -> str: return "~" -def _extract_in(node: NodeIn, **kwargs: Any) -> str: +def _extract_in(node: ast.In, **kwargs: Any) -> str: return "in" -def _extract_is(node: NodeIs, **kwargs: Any) -> str: +def _extract_is(node: ast.Is, **kwargs: Any) -> str: return "is" -def _extract_isnot(node: NodeIsNot, **kwargs: Any) -> str: +def _extract_isnot(node: ast.IsNot, **kwargs: Any) -> str: return "is not" -def _extract_joinedstr(node: NodeJoinedStr, **kwargs: Any) -> str: +def _extract_joinedstr(node: ast.JoinedStr, **kwargs: Any) -> str: return "f" + repr("".join(_extract(value, in_joined_str=True, **kwargs) for value in node.values)) -def _extract_keyword(node: NodeKeyword, **kwargs: Any) -> str: +def _extract_keyword(node: ast.keyword, **kwargs: Any) -> str: if node.arg is None: return f"**{_extract(node.value, **kwargs)}" return f"{node.arg}={_extract(node.value, **kwargs)}" -def _extract_lambda(node: NodeLambda, **kwargs: Any) -> str: +def _extract_lambda(node: ast.Lambda, **kwargs: Any) -> str: return f"lambda {_extract(node.args, **kwargs)}: {_extract(node.body, **kwargs)}" -def _extract_list(node: NodeList, **kwargs: Any) -> str: +def _extract_list(node: ast.List, **kwargs: Any) -> str: return "[" + ", ".join(_extract(el, **kwargs) for el in node.elts) + "]" -def _extract_listcomp(node: NodeListComp, **kwargs: Any) -> str: +def _extract_listcomp(node: ast.ListComp, **kwargs: Any) -> str: element = _extract(node.elt, **kwargs) generators = [_extract(gen, **kwargs) for gen in node.generators] return f"[{element} " + " ".join(generators) + "]" -def _extract_lshift(node: NodeLShift, **kwargs: Any) -> str: +def _extract_lshift(node: ast.LShift, **kwargs: Any) -> str: return "<<" -def _extract_lte(node: NodeNotEq, **kwargs: Any) -> str: +def _extract_lte(node: ast.NotEq, **kwargs: Any) -> str: return "<=" -def _extract_lt(node: NodeNotEq, **kwargs: Any) -> str: +def _extract_lt(node: ast.NotEq, **kwargs: Any) -> str: return "<" -def _extract_matmult(node: NodeMatMult, **kwargs: Any) -> str: +def _extract_matmult(node: ast.MatMult, **kwargs: Any) -> str: return "@" -def _extract_mod(node: NodeMod, **kwargs: Any) -> str: +def _extract_mod(node: ast.Mod, **kwargs: Any) -> str: return "%" -def _extract_mult(node: NodeMult, **kwargs: Any) -> str: +def _extract_mult(node: ast.Mult, **kwargs: Any) -> str: return "*" -def _extract_name(node: NodeName, **kwargs: Any) -> str: +def _extract_name(node: ast.Name, **kwargs: Any) -> str: return node.id -def _extract_named_expr(node: NodeNamedExpr, **kwargs: Any) -> str: +def _extract_named_expr(node: ast.NamedExpr, **kwargs: Any) -> str: return f"({_extract(node.target, **kwargs)} := {_extract(node.value, **kwargs)})" -def _extract_not(node: NodeNot, **kwargs: Any) -> str: +def _extract_not(node: ast.Not, **kwargs: Any) -> str: return "not " -def _extract_noteq(node: NodeNotEq, **kwargs: Any) -> str: +def _extract_noteq(node: ast.NotEq, **kwargs: Any) -> str: return "!=" -def _extract_notin(node: NodeNotIn, **kwargs: Any) -> str: +def _extract_notin(node: ast.NotIn, **kwargs: Any) -> str: return "not in" -def _extract_or(node: NodeOr, **kwargs: Any) -> str: +def _extract_or(node: ast.Or, **kwargs: Any) -> str: return "or" -def _extract_pow(node: NodePow, **kwargs: Any) -> str: +def _extract_pow(node: ast.Pow, **kwargs: Any) -> str: return "**" -def _extract_rshift(node: NodeRShift, **kwargs: Any) -> str: +def _extract_rshift(node: ast.RShift, **kwargs: Any) -> str: return ">>" -def _extract_set(node: NodeSet, **kwargs: Any) -> str: +def _extract_set(node: ast.Set, **kwargs: Any) -> str: return "{" + ", ".join(_extract(el, **kwargs) for el in node.elts) + "}" -def _extract_setcomp(node: NodeSetComp, **kwargs: Any) -> str: +def _extract_setcomp(node: ast.SetComp, **kwargs: Any) -> str: element = _extract(node.elt, **kwargs) generators = [_extract(gen, **kwargs) for gen in node.generators] return f"{{{element} " + " ".join(generators) + "}" -def _extract_slice(node: NodeSlice, **kwargs: Any) -> str: +def _extract_slice(node: ast.Slice, **kwargs: Any) -> str: lower = _extract(node.lower, **kwargs) if node.lower else "" upper = _extract(node.upper, **kwargs) if node.upper else "" value = f"{lower}:{upper}" @@ -325,122 +258,121 @@ def _extract_slice(node: NodeSlice, **kwargs: Any) -> str: return value -def _extract_starred(node: NodeStarred, **kwargs: Any) -> str: +def _extract_starred(node: ast.Starred, **kwargs: Any) -> str: return f"*{_extract(node.value, **kwargs)}" -def _extract_sub(node: NodeSub, **kwargs: Any) -> str: +def _extract_sub(node: ast.Sub, **kwargs: Any) -> str: return "-" -def _extract_subscript(node: NodeSubscript, **kwargs: Any) -> str: +def _extract_subscript(node: ast.Subscript, **kwargs: Any) -> str: subscript = _extract(node.slice, **kwargs) if isinstance(subscript, str) and subscript.startswith("(") and subscript.endswith(")"): subscript = subscript[1:-1] return f"{_extract(node.value, **kwargs)}[{subscript}]" -def _extract_tuple(node: NodeTuple, **kwargs: Any) -> str: +def _extract_tuple(node: ast.Tuple, **kwargs: Any) -> str: return "(" + ", ".join(_extract(el, **kwargs) for el in node.elts) + ")" -def _extract_uadd(node: NodeUAdd, **kwargs: Any) -> str: +def _extract_uadd(node: ast.UAdd, **kwargs: Any) -> str: return "+" -def _extract_unaryop(node: NodeUnaryOp, **kwargs: Any) -> str: +def _extract_unaryop(node: ast.UnaryOp, **kwargs: Any) -> str: return f"{_extract(node.op, **kwargs)}{_extract(node.operand, **kwargs)}" -def _extract_usub(node: NodeUSub, **kwargs: Any) -> str: +def _extract_usub(node: ast.USub, **kwargs: Any) -> str: return "-" -def _extract_yield(node: NodeYield, **kwargs: Any) -> str: +def _extract_yield(node: ast.Yield, **kwargs: Any) -> str: if node.value is None: return repr(None) return _extract(node.value, **kwargs) _node_map: dict[type, Callable[[Any], str]] = { - NodeAdd: _extract_add, - NodeAnd: _extract_and, - NodeArguments: _extract_arguments, - NodeAttribute: _extract_attribute, - NodeBinOp: _extract_binop, - NodeBitAnd: _extract_bitand, - NodeBitOr: _extract_bitor, - NodeBitXor: _extract_bitxor, - NodeBoolOp: _extract_boolop, - NodeCall: _extract_call, - NodeCompare: _extract_compare, - NodeComprehension: _extract_comprehension, - NodeConstant: _extract_constant, - NodeDictComp: _extract_dictcomp, - NodeDict: _extract_dict, - NodeDiv: _extract_div, - NodeEllipsis: _extract_ellipsis, - NodeEq: _extract_eq, - NodeFloorDiv: _extract_floordiv, - NodeFormattedValue: _extract_formatted, - NodeGeneratorExp: _extract_generatorexp, - NodeGtE: _extract_gte, - NodeGt: _extract_gt, - NodeIfExp: _extract_ifexp, - NodeIn: _extract_in, - NodeInvert: _extract_invert, - NodeIs: _extract_is, - NodeIsNot: _extract_isnot, - NodeJoinedStr: _extract_joinedstr, - NodeKeyword: _extract_keyword, - NodeLambda: _extract_lambda, - NodeListComp: _extract_listcomp, - NodeList: _extract_list, - NodeLShift: _extract_lshift, - NodeLtE: _extract_lte, - NodeLt: _extract_lt, - NodeMatMult: _extract_matmult, - NodeMod: _extract_mod, - NodeMult: _extract_mult, - NodeName: _extract_name, - NodeNamedExpr: _extract_named_expr, - NodeNotEq: _extract_noteq, - NodeNot: _extract_not, - NodeNotIn: _extract_notin, - NodeOr: _extract_or, - NodePow: _extract_pow, - NodeRShift: _extract_rshift, - NodeSetComp: _extract_setcomp, - NodeSet: _extract_set, - NodeSlice: _extract_slice, - NodeStarred: _extract_starred, - NodeSub: _extract_sub, - NodeSubscript: _extract_subscript, - NodeTuple: _extract_tuple, - NodeUAdd: _extract_uadd, - NodeUnaryOp: _extract_unaryop, - NodeUSub: _extract_usub, - NodeYield: _extract_yield, + ast.Add: _extract_add, + ast.And: _extract_and, + ast.arguments: _extract_arguments, + ast.Attribute: _extract_attribute, + ast.BinOp: _extract_binop, + ast.BitAnd: _extract_bitand, + ast.BitOr: _extract_bitor, + ast.BitXor: _extract_bitxor, + ast.BoolOp: _extract_boolop, + ast.Call: _extract_call, + ast.Compare: _extract_compare, + ast.comprehension: _extract_comprehension, + ast.Constant: _extract_constant, + ast.DictComp: _extract_dictcomp, + ast.Dict: _extract_dict, + ast.Div: _extract_div, + ast.Eq: _extract_eq, + ast.FloorDiv: _extract_floordiv, + ast.FormattedValue: _extract_formatted, + ast.GeneratorExp: _extract_generatorexp, + ast.GtE: _extract_gte, + ast.Gt: _extract_gt, + ast.IfExp: _extract_ifexp, + ast.In: _extract_in, + ast.Invert: _extract_invert, + ast.Is: _extract_is, + ast.IsNot: _extract_isnot, + ast.JoinedStr: _extract_joinedstr, + ast.keyword: _extract_keyword, + ast.Lambda: _extract_lambda, + ast.ListComp: _extract_listcomp, + ast.List: _extract_list, + ast.LShift: _extract_lshift, + ast.LtE: _extract_lte, + ast.Lt: _extract_lt, + ast.MatMult: _extract_matmult, + ast.Mod: _extract_mod, + ast.Mult: _extract_mult, + ast.Name: _extract_name, + ast.NamedExpr: _extract_named_expr, + ast.NotEq: _extract_noteq, + ast.Not: _extract_not, + ast.NotIn: _extract_notin, + ast.Or: _extract_or, + ast.Pow: _extract_pow, + ast.RShift: _extract_rshift, + ast.SetComp: _extract_setcomp, + ast.Set: _extract_set, + ast.Slice: _extract_slice, + ast.Starred: _extract_starred, + ast.Sub: _extract_sub, + ast.Subscript: _extract_subscript, + ast.Tuple: _extract_tuple, + ast.UAdd: _extract_uadd, + ast.UnaryOp: _extract_unaryop, + ast.USub: _extract_usub, + ast.Yield: _extract_yield, } # TODO: remove once Python 3.8 support is if sys.version_info < (3, 9): - def _extract_extslice(node: NodeExtSlice, **kwargs: Any) -> str: + def _extract_extslice(node: ast.ExtSlice, **kwargs: Any) -> str: return ",".join(_extract(dim, **kwargs) for dim in node.dims) - def _extract_index(node: NodeIndex, **kwargs: Any) -> str: + def _extract_index(node: ast.Index, **kwargs: Any) -> str: return _extract(node.value, **kwargs) - _node_map[NodeExtSlice] = _extract_extslice - _node_map[NodeIndex] = _extract_index + _node_map[ast.ExtSlice] = _extract_extslice + _node_map[ast.Index] = _extract_index -def _extract(node: AST, **kwargs: Any) -> str: +def _extract(node: ast.AST, **kwargs: Any) -> str: return _node_map[type(node)](node, **kwargs) -def get_value(node: AST | None) -> str | None: +def get_value(node: ast.AST | None) -> str | None: """Get the string representation of a node. Parameters: @@ -454,7 +386,7 @@ def get_value(node: AST | None) -> str | None: return _extract(node) -def safe_get_value(node: AST | None, filepath: str | Path | None = None) -> str | None: +def safe_get_value(node: ast.AST | None, filepath: str | Path | None = None) -> str | None: """Safely (no exception) get the string representation of a node. Parameters: diff --git a/src/griffe/finder.py b/src/griffe/finder.py index 79acf8ad..10b7e0e6 100644 --- a/src/griffe/finder.py +++ b/src/griffe/finder.py @@ -362,7 +362,7 @@ def _handle_editable_module(path: Path) -> list[Path]: and isinstance(node.targets[0], ast.Name) and node.targets[0].id == "MAPPING" ) and isinstance(node.value, ast.Dict): - return [Path(constant.s).parent for constant in node.value.values if isinstance(constant, ast.Str)] + return [Path(cst.value).parent for cst in node.value.values if isinstance(cst, ast.Constant)] raise UnhandledEditableModuleError(path)