Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/astroid/brain/brain_numpy_utils.py: 65%
26 statements
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-07 06:53 +0000
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-07 06:53 +0000
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
5"""Different utilities for the numpy brains."""
7from __future__ import annotations
9from astroid.builder import extract_node
10from astroid.context import InferenceContext
11from astroid.nodes.node_classes import Attribute, Import, Name
13# Class subscript is available in numpy starting with version 1.20.0
14NUMPY_VERSION_TYPE_HINTS_SUPPORT = ("1", "20", "0")
17def numpy_supports_type_hints() -> bool:
18 """Returns True if numpy supports type hints."""
19 np_ver = _get_numpy_version()
20 return np_ver and np_ver > NUMPY_VERSION_TYPE_HINTS_SUPPORT
23def _get_numpy_version() -> tuple[str, str, str]:
24 """
25 Return the numpy version number if numpy can be imported.
27 Otherwise returns ('0', '0', '0')
28 """
29 try:
30 import numpy # pylint: disable=import-outside-toplevel
32 return tuple(numpy.version.version.split("."))
33 except (ImportError, AttributeError):
34 return ("0", "0", "0")
37def infer_numpy_member(src, node, context: InferenceContext | None = None):
38 node = extract_node(src)
39 return node.infer(context=context)
42def _is_a_numpy_module(node: Name) -> bool:
43 """
44 Returns True if the node is a representation of a numpy module.
46 For example in :
47 import numpy as np
48 x = np.linspace(1, 2)
49 The node <Name.np> is a representation of the numpy module.
51 :param node: node to test
52 :return: True if the node is a representation of the numpy module.
53 """
54 module_nickname = node.name
55 potential_import_target = [
56 x for x in node.lookup(module_nickname)[1] if isinstance(x, Import)
57 ]
58 return any(
59 ("numpy", module_nickname) in target.names or ("numpy", None) in target.names
60 for target in potential_import_target
61 )
64def name_looks_like_numpy_member(member_name: str, node: Name) -> bool:
65 """
66 Returns True if the Name is a member of numpy whose
67 name is member_name.
68 """
69 return node.name == member_name and node.root().name.startswith("numpy")
72def attribute_looks_like_numpy_member(member_name: str, node: Attribute) -> bool:
73 """
74 Returns True if the Attribute is a member of numpy whose
75 name is member_name.
76 """
77 return (
78 node.attrname == member_name
79 and isinstance(node.expr, Name)
80 and _is_a_numpy_module(node.expr)
81 )