Coverage for src/pylint_sort_functions/utils/ast_analysis.py: 100%

1"""AST analysis utilities for function and method extraction.

2

3 This module provides core AST analysis functions for extracting and analyzing

4 function and method definitions from Python code.

5"""

6

7 from astroid import nodes # type: ignore[import-untyped]

8

9

10 def get_functions_from_node(node: nodes.Module) -> list[nodes.FunctionDef]:

11 """Extract all function definitions from a module.

12

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

23

24

25 def get_methods_from_class(node: nodes.ClassDef) -> list[nodes.FunctionDef]:

26 """Extract all method definitions from a class.

27

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

38

39

40 def is_dunder_method(func: nodes.FunctionDef) -> bool:

41 """Check if a function is a dunder/magic method.

42

43 Dunder methods are special methods that start and end with double underscores,

44 like __init__, __str__, __call__, etc.

45

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("__")

53

54

55 def is_private_function(func: nodes.FunctionDef) -> bool:

56 """Check if a function is private (starts with underscore).

57

58 DEPRECATED: This function is maintained for backward compatibility.

59 New code should use categorize_method() with appropriate configuration.

60

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.

64

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)