Skip to content

Commit

Permalink
Catch ImportWarning when compiling or loading cython string co-effici…
Browse files Browse the repository at this point in the history
…ents for Python 3.10.
  • Loading branch information
hodgestar committed Feb 2, 2022
1 parent ce98808 commit 299f22b
Showing 1 changed file with 18 additions and 7 deletions.
25 changes: 18 additions & 7 deletions qutip/core/coefficient.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,7 @@
import hashlib
import glob
import importlib
import inspect
import shutil
import warnings
import numbers
from contextlib import contextmanager
from collections import defaultdict
Expand All @@ -18,7 +17,6 @@
from Cython.Build import cythonize
except ImportError:
pass
from warnings import warn

from ..settings import settings as qset
from ..optionsclass import optionsclass
Expand All @@ -33,6 +31,17 @@
"clean_compiled_coefficient"]


@contextmanager
def _ignore_import_warning_for_pyximporter():
"""
A helper for ignoring PyxImporter import warnings generated by Python 3.10+
because PyxImporter has no .find_spec method.
"""
with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=ImportWarning)
yield


class StringParsingWarning(Warning):
pass

Expand Down Expand Up @@ -348,9 +357,9 @@ def try_import(file_name, parsed_in):
name collision.
"""
get_root()
coeff = None
try:
mod = importlib.import_module(file_name)
with _ignore_import_warning_for_pyximporter():
mod = importlib.import_module(file_name)
except ModuleNotFoundError:
# Coefficient does not exist, to compile as file_name
return None
Expand Down Expand Up @@ -486,7 +495,9 @@ def compile_code(code, file_name, parsed, c_opt):
include_dirs=[np.get_include()],
language='c++'
)
setup(ext_modules=cythonize(coeff_file, force=c_opt['recompile']))
with _ignore_import_warning_for_pyximporter():
ext_modules = cythonize(coeff_file, force=c_opt['recompile'])
setup(ext_modules=ext_modules)
except Exception as e:
raise Exception("Could not compile") from e
finally:
Expand Down Expand Up @@ -691,7 +702,7 @@ def try_parse(code, args, args_ctypes, compile_opt):
):
return ncode, variables, constants, False
else:
warn("Could not find c types", StringParsingWarning)
warnings.warn("Could not find c types", StringParsingWarning)
remaped_variable = []
for _, name, ctype in variables:
remaped_variable.append(("self." + name, name, "object"))
Expand Down

0 comments on commit 299f22b

Please sign in to comment.