Coverage for src/pylint_sort_functions/utils/ast_analysis.py: 100%
18 statements
« prev ^ index » next coverage.py v7.10.1, created at 2025-08-12 16:06 +0200
« prev ^ index » next coverage.py v7.10.1, created at 2025-08-12 16:06 +0200
1"""AST analysis utilities for function and method extraction.
3This module provides core AST analysis functions for extracting and analyzing
4function and method definitions from Python code.
5"""
7from astroid import nodes # type: ignore[import-untyped]
10def get_functions_from_node(node: nodes.Module) -> list[nodes.FunctionDef]:
11 """Extract all function definitions from a module.
13 :param node: Module AST node
14 :type node: nodes.Module
15 :returns: List of function definition nodes
16 :rtype: list[nodes.FunctionDef]
17 """
18 functions = []
19 for child in node.body:
20 if isinstance(child, nodes.FunctionDef):
21 functions.append(child)
22 return functions
25def get_methods_from_class(node: nodes.ClassDef) -> list[nodes.FunctionDef]:
26 """Extract all method definitions from a class.
28 :param node: Class definition node
29 :type node: nodes.ClassDef
30 :returns: List of method definition nodes
31 :rtype: list[nodes.FunctionDef]
32 """
33 methods = []
34 for child in node.body:
35 if isinstance(child, nodes.FunctionDef):
36 methods.append(child)
37 return methods
40def is_dunder_method(func: nodes.FunctionDef) -> bool:
41 """Check if a function is a dunder/magic method.
43 Dunder methods are special methods that start and end with double underscores,
44 like __init__, __str__, __call__, etc.
46 :param func: Function definition node
47 :type func: nodes.FunctionDef
48 :returns: True if function is a dunder method
49 :rtype: bool
50 """
51 name: str = func.name # Explicitly typed to satisfy mypy
52 return name.startswith("__") and name.endswith("__")
55def is_private_function(func: nodes.FunctionDef) -> bool:
56 """Check if a function is private (starts with underscore).
58 DEPRECATED: This function is maintained for backward compatibility.
59 New code should use categorize_method() with appropriate configuration.
61 Functions starting with a single underscore are considered private by convention.
62 Dunder methods (double underscore) like __init__ are not considered private
63 as they are special methods with specific meanings in Python.
65 :param func: Function definition node
66 :type func: nodes.FunctionDef
67 :returns: True if function name starts with underscore but not double underscore
68 :rtype: bool
69 """
70 return func.name.startswith("_") and not is_dunder_method(func)