Skip to content

Commit 45a6e87

Browse files
committed
BF: be resilient to optional module non-ImportError exceptions upon import
ATM h5py is giving a grief while trying to work on a filesystem without utf-8 encoding support in filenames.
1 parent 2817d1b commit 45a6e87

File tree

2 files changed

+15
-3
lines changed

2 files changed

+15
-3
lines changed

nibabel/optpkg.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -94,9 +94,14 @@ def optional_package(name, trip_msg=None, min_version=None):
9494
# fromlist=[''] results in submodule being returned, rather than the top
9595
# level module. See help(__import__)
9696
fromlist = [''] if '.' in name else []
97+
exc = None
9798
try:
9899
pkg = __import__(name, fromlist=fromlist)
99-
except ImportError:
100+
except ImportError as exc:
101+
pass
102+
except Exception as exc: # it failed to import for some other reason
103+
# e.g. h5py might have been checking file system to support UTF-8
104+
# etc. We should not blow if they blow
100105
pass
101106
else: # import worked
102107
# top level module
@@ -111,8 +116,8 @@ def optional_package(name, trip_msg=None, min_version=None):
111116
(name, min_version))
112117
if trip_msg is None:
113118
trip_msg = ('We need package %s for these functions, but '
114-
'``import %s`` raised an ImportError'
115-
% (name, name))
119+
'``import %s`` raised %s'
120+
% (name, name, exc))
116121
pkg = TripWire(trip_msg)
117122

118123
def setup_module():

nibabel/tests/test_optpkg.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
""" Testing optpkg module
22
"""
33

4+
import mock
45
import types
56
import sys
67
from distutils.version import LooseVersion
@@ -36,6 +37,12 @@ def test_basic():
3637
assert_good('os.path')
3738
# We never have package _not_a_package
3839
assert_bad('_not_a_package')
40+
def raise_Exception(*args, **kwargs):
41+
raise Exception(
42+
"non ImportError could be thrown by some malfunctioning module "
43+
"upon import, and optional_package should catch it too")
44+
with mock.patch('__builtin__.__import__', side_effect=raise_Exception):
45+
assert_bad('nottriedbefore')
3946

4047

4148
def test_versions():

0 commit comments

Comments
 (0)