From b1fd84134ed96e0abb82fa56c010bd4ad1d5ddb2 Mon Sep 17 00:00:00 2001 From: Mehdi Drissi Date: Tue, 9 May 2023 00:27:17 -0700 Subject: [PATCH 1/3] Add brain to fix tensorflow import errors. --- astroid/brain/brain_tensorflow.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 astroid/brain/brain_tensorflow.py diff --git a/astroid/brain/brain_tensorflow.py b/astroid/brain/brain_tensorflow.py new file mode 100644 index 0000000000..f53cf012b7 --- /dev/null +++ b/astroid/brain/brain_tensorflow.py @@ -0,0 +1,14 @@ +"""Astroid hooks for understanding tensorflow's imports.""" +from astroid import MANAGER +from astroid.exceptions import AstroidBuildingError + + +def _tensorflow_fail_hook(modname: str): + parts = modname.split(".", 1) + if parts[0] == "tensorflow": + parts[0] = "tensorflow.python" + return MANAGER.ast_from_module_name(".".join(parts)) + raise AstroidBuildingError(modname=modname) + + +MANAGER.register_failed_import_hook(_tensorflow_fail_hook) From 7a7a58270d2bab9b45f31d4fbf8fe55e6e7965d2 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Tue, 9 May 2023 07:34:33 +0000 Subject: [PATCH 2/3] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- astroid/brain/brain_tensorflow.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/astroid/brain/brain_tensorflow.py b/astroid/brain/brain_tensorflow.py index f53cf012b7..004421b178 100644 --- a/astroid/brain/brain_tensorflow.py +++ b/astroid/brain/brain_tensorflow.py @@ -1,3 +1,6 @@ +# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html +# For details: https://github.com/pylint-dev/astroid/blob/main/LICENSE +# Copyright (c) https://github.com/pylint-dev/astroid/blob/main/CONTRIBUTORS.txt """Astroid hooks for understanding tensorflow's imports.""" from astroid import MANAGER from astroid.exceptions import AstroidBuildingError From 04115057e197e4ea4e4334848a738e9651e8fe30 Mon Sep 17 00:00:00 2001 From: Mehdi Drissi Date: Tue, 9 May 2023 10:45:08 -0700 Subject: [PATCH 3/3] Avoid recursion in tensorflow import fallback. --- astroid/brain/brain_tensorflow.py | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/astroid/brain/brain_tensorflow.py b/astroid/brain/brain_tensorflow.py index 004421b178..446ee1501d 100644 --- a/astroid/brain/brain_tensorflow.py +++ b/astroid/brain/brain_tensorflow.py @@ -8,9 +8,15 @@ def _tensorflow_fail_hook(modname: str): parts = modname.split(".", 1) + fallbacks = ("python", "_api.v2") if parts[0] == "tensorflow": - parts[0] = "tensorflow.python" - return MANAGER.ast_from_module_name(".".join(parts)) + for fallback in fallbacks: + if parts[1].startswith(fallbacks): + continue + try: + return MANAGER.ast_from_module_name(f"tensorflow.{fallback}.{parts[1]}") + except AstroidBuildingError: + continue raise AstroidBuildingError(modname=modname)