From bf92064aff50178038ccb579881b47213b62efa8 Mon Sep 17 00:00:00 2001 From: fumoboy007 <2100868+fumoboy007@users.noreply.github.com> Date: Mon, 16 Sep 2024 14:27:26 -0700 Subject: [PATCH] Propagate Pandas/Polars import errors when the module exists but failed to be imported. Broadly speaking, there are two categories of `ImportError`: the module does not exist, or the module exists but failed to be imported. Currently, both are silently ignored; however, the latter category of error should be propagated up the stack so that the developer can investigate and resolve the issue. --- talib/__init__.py | 20 ++++++++++++++++++-- talib/_abstract.pxi | 20 ++++++++++++++++++-- 2 files changed, 36 insertions(+), 4 deletions(-) diff --git a/talib/__init__.py b/talib/__init__.py index 4a7eea920..f215cd9e7 100644 --- a/talib/__init__.py +++ b/talib/__init__.py @@ -7,7 +7,15 @@ # polars.Series input try: from polars import Series as _pl_Series -except ImportError: +except ImportError as import_error: + try: + if not isinstance(import_error, ModuleNotFoundError) or import_error.name != 'polars': + # Propagate the error when the module exists but failed to be imported. + raise import_error + # `ModuleNotFoundError` was introduced in Python 3.6. + except NameError: + pass + # polars not available, nothing to wrap _pl_Series = None @@ -15,7 +23,15 @@ # pandas.Series input try: from pandas import Series as _pd_Series -except ImportError: +except ImportError as import_error: + try: + if not isinstance(import_error, ModuleNotFoundError) or import_error.name != 'pandas': + # Propagate the error when the module exists but failed to be imported. + raise import_error + # `ModuleNotFoundError` was introduced in Python 3.6. + except NameError: + pass + # pandas not available, nothing to wrap _pd_Series = None diff --git a/talib/_abstract.pxi b/talib/_abstract.pxi index b3c1e6c72..8fb8089ae 100644 --- a/talib/_abstract.pxi +++ b/talib/_abstract.pxi @@ -34,7 +34,15 @@ try: __ARRAY_TYPES.append(pandas.Series) __PANDAS_DATAFRAME = pandas.DataFrame __PANDAS_SERIES = pandas.Series -except ImportError: +except ImportError as import_error: + try: + if not isinstance(import_error, ModuleNotFoundError) or import_error.name != 'pandas': + # Propagate the error when the module exists but failed to be imported. + raise import_error + # `ModuleNotFoundError` was introduced in Python 3.6. + except NameError: + pass + __PANDAS_DATAFRAME = None __PANDAS_SERIES = None @@ -45,7 +53,15 @@ try: __ARRAY_TYPES.append(polars.Series) __POLARS_DATAFRAME = polars.DataFrame __POLARS_SERIES = polars.Series -except ImportError: +except ImportError as import_error: + try: + if not isinstance(import_error, ModuleNotFoundError) or import_error.name != 'polars': + # Propagate the error when the module exists but failed to be imported. + raise import_error + # `ModuleNotFoundError` was introduced in Python 3.6. + except NameError: + pass + __POLARS_DATAFRAME = None __POLARS_SERIES = None