brain_numpy_utils.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. # Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
  2. # For details: https://github.com/PyCQA/astroid/blob/main/LICENSE
  3. # Copyright (c) https://github.com/PyCQA/astroid/blob/main/CONTRIBUTORS.txt
  4. """Different utilities for the numpy brains."""
  5. from __future__ import annotations
  6. from astroid.builder import extract_node
  7. from astroid.context import InferenceContext
  8. from astroid.nodes.node_classes import Attribute, Import, Name, NodeNG
  9. # Class subscript is available in numpy starting with version 1.20.0
  10. NUMPY_VERSION_TYPE_HINTS_SUPPORT = ("1", "20", "0")
  11. def numpy_supports_type_hints() -> bool:
  12. """Returns True if numpy supports type hints."""
  13. np_ver = _get_numpy_version()
  14. return np_ver and np_ver > NUMPY_VERSION_TYPE_HINTS_SUPPORT
  15. def _get_numpy_version() -> tuple[str, str, str]:
  16. """
  17. Return the numpy version number if numpy can be imported.
  18. Otherwise returns ('0', '0', '0')
  19. """
  20. try:
  21. import numpy # pylint: disable=import-outside-toplevel
  22. return tuple(numpy.version.version.split("."))
  23. except (ImportError, AttributeError):
  24. return ("0", "0", "0")
  25. def infer_numpy_member(src, node, context: InferenceContext | None = None):
  26. node = extract_node(src)
  27. return node.infer(context=context)
  28. def _is_a_numpy_module(node: Name) -> bool:
  29. """
  30. Returns True if the node is a representation of a numpy module.
  31. For example in :
  32. import numpy as np
  33. x = np.linspace(1, 2)
  34. The node <Name.np> is a representation of the numpy module.
  35. :param node: node to test
  36. :return: True if the node is a representation of the numpy module.
  37. """
  38. module_nickname = node.name
  39. potential_import_target = [
  40. x for x in node.lookup(module_nickname)[1] if isinstance(x, Import)
  41. ]
  42. return any(
  43. ("numpy", module_nickname) in target.names or ("numpy", None) in target.names
  44. for target in potential_import_target
  45. )
  46. def looks_like_numpy_member(member_name: str, node: NodeNG) -> bool:
  47. """
  48. Returns True if the node is a member of numpy whose
  49. name is member_name.
  50. :param member_name: name of the member
  51. :param node: node to test
  52. :return: True if the node is a member of numpy
  53. """
  54. if (
  55. isinstance(node, Attribute)
  56. and node.attrname == member_name
  57. and isinstance(node.expr, Name)
  58. and _is_a_numpy_module(node.expr)
  59. ):
  60. return True
  61. if (
  62. isinstance(node, Name)
  63. and node.name == member_name
  64. and node.root().name.startswith("numpy")
  65. ):
  66. return True
  67. return False