Skip to content

Commit a8cf459

Browse files
committed
Fix ImportFinder/Loader for Python 2
The value of sys.meta_path varies with the Python version. Signed-off-by: Sebastian Ramacher <sebastian+dev@ramacher.at>
1 parent d071969 commit a8cf459

File tree

1 file changed

+35
-2
lines changed

1 file changed

+35
-2
lines changed

bpython/curtsiesfrontend/repl.py

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,9 @@
5353

5454
from curtsies.configfile_keynames import keymap as key_dispatch
5555

56+
if not py3:
57+
import imp
58+
5659

5760
logger = logging.getLogger(__name__)
5861

@@ -220,13 +223,34 @@ def __init__(self, watcher, loader):
220223
self.watcher = watcher
221224
self.loader = loader
222225

223-
def load_module(self, fullname):
224-
module = self.loader.load_module(fullname)
226+
def load_module(self, name):
227+
module = self.loader.load_module(name)
225228
if hasattr(module, '__file__'):
226229
self.watcher.track_module(module.__file__)
227230
return module
228231

229232

233+
if not py3:
234+
class ImpImportLoader(object):
235+
236+
def __init__(self, watcher, file, pathname, description):
237+
self.watcher = watcher
238+
self.file = file
239+
self.pathname = pathname
240+
self.description = description
241+
242+
def load_module(self, name):
243+
try:
244+
module = imp.load_module(name, self.file, self.pathname,
245+
self.description)
246+
if hasattr(module, '__file__'):
247+
self.watcher.track_module(module.__file__)
248+
return module
249+
finally:
250+
if self.file is not None:
251+
self.file.close()
252+
253+
230254
class ImportFinder(object):
231255

232256
def __init__(self, watcher, old_meta_path):
@@ -239,6 +263,15 @@ def find_module(self, fullname, path=None):
239263
if loader is not None:
240264
return ImportLoader(self.watcher, loader)
241265

266+
if not py3:
267+
# Python 2 does not have the default finders stored in
268+
# sys.meta_path. Use imp to perform the actual importing.
269+
try:
270+
result = imp.find_module(fullname, path)
271+
return ImpImportLoader(self.watcher, *result)
272+
except ImportError:
273+
return None
274+
242275
return None
243276

244277

0 commit comments

Comments
 (0)