1# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
2# For details: https://github.com/pylint-dev/astroid/blob/main/LICENSE
3# Copyright (c) https://github.com/pylint-dev/astroid/blob/main/CONTRIBUTORS.txt
4
5"""Different utilities for the numpy brains."""
6
7from __future__ import annotations
8
9from functools import lru_cache
10from importlib import metadata
11
12from astroid import nodes
13from astroid.builder import extract_node
14from astroid.context import InferenceContext
15
16# Class subscript is available in numpy starting with version 1.20.0
17NUMPY_VERSION_TYPE_HINTS_SUPPORT = ("1", "20", "0")
18
19
20def numpy_supports_type_hints() -> bool:
21 """Returns True if numpy supports type hints."""
22 np_ver = _get_numpy_version()
23 return np_ver and np_ver > NUMPY_VERSION_TYPE_HINTS_SUPPORT
24
25
26def numpy_version_2_or_later() -> bool:
27 """Returns True if the installed numpy is version 2 or later."""
28 try:
29 return int(_get_numpy_version()[0]) >= 2
30 except ValueError:
31 return False
32
33
34@lru_cache
35def _get_numpy_version() -> tuple[str, str, str]:
36 """
37 Return the numpy version number if numpy is installed.
38
39 Otherwise returns ('0', '0', '0'). Read from the package metadata rather
40 than by importing numpy, which may resolve to the analysed code.
41 """
42 try:
43 return tuple(metadata.version("numpy").split("."))
44 except metadata.PackageNotFoundError:
45 return ("0", "0", "0")
46
47
48def infer_numpy_name(
49 sources: dict[str, str], node: nodes.Name, context: InferenceContext | None = None
50):
51 extracted_node = extract_node(sources[node.name])
52 return extracted_node.infer(context=context)
53
54
55def infer_numpy_attribute(
56 sources: dict[str, str],
57 node: nodes.Attribute,
58 context: InferenceContext | None = None,
59):
60 extracted_node = extract_node(sources[node.attrname])
61 return extracted_node.infer(context=context)
62
63
64def _is_a_numpy_module(node: nodes.Name) -> bool:
65 """
66 Returns True if the node is a representation of a numpy module.
67
68 For example in :
69 import numpy as np
70 x = np.linspace(1, 2)
71 The node <Name.np> is a representation of the numpy module.
72
73 :param node: node to test
74 :return: True if the node is a representation of the numpy module.
75 """
76 module_nickname = node.name
77 potential_import_target = [
78 x for x in node.lookup(module_nickname)[1] if isinstance(x, nodes.Import)
79 ]
80 return any(
81 ("numpy", module_nickname) in target.names or ("numpy", None) in target.names
82 for target in potential_import_target
83 )
84
85
86def member_name_looks_like_numpy_member(
87 member_names: frozenset[str], node: nodes.Name
88) -> bool:
89 """
90 Returns True if the Name node's name matches a member name from numpy
91 """
92 return node.name in member_names and node.root().name.startswith("numpy")
93
94
95def attribute_name_looks_like_numpy_member(
96 member_names: frozenset[str], node: nodes.Attribute
97) -> bool:
98 """
99 Returns True if the Attribute node's name matches a member name from numpy
100 """
101 return (
102 node.attrname in member_names
103 and isinstance(node.expr, nodes.Name)
104 and _is_a_numpy_module(node.expr)
105 )