Skip to content

Commit 1a674f0

Browse files
committed
Use importlib for Python 3 (fixes bpython#791)
1 parent e9651ae commit 1a674f0

File tree

1 file changed

+19
-6
lines changed

1 file changed

+19
-6
lines changed

bpython/importcompletion.py

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,6 @@
3232
current_from_import_import,
3333
)
3434

35-
import imp
3635
import os
3736
import sys
3837
import warnings
@@ -143,6 +142,10 @@ def find_modules(path):
143142
filenames = os.listdir(path)
144143
except EnvironmentError:
145144
filenames = []
145+
146+
if py3:
147+
finder = importlib.machinery.FileFinder(path)
148+
146149
for name in filenames:
147150
if not any(name.endswith(suffix) for suffix in SUFFIXES):
148151
# Possibly a package
@@ -163,12 +166,22 @@ def find_modules(path):
163166
is_package = False
164167
with warnings.catch_warnings():
165168
warnings.simplefilter("ignore", ImportWarning)
166-
fo, pathname, _ = imp.find_module(name, [path])
167-
if fo is not None:
168-
fo.close()
169+
if py3:
170+
spec = finder.find_spec(name)
171+
if spec is None:
172+
continue
173+
if spec.submodule_search_locations is not None:
174+
pathname = spec.submodule_search_locations[0]
175+
is_package = True
176+
else:
177+
pathname = spec.origin
169178
else:
170-
# Yay, package
171-
is_package = True
179+
fo, pathname, _ = imp.find_module(name, [path])
180+
if fo is not None:
181+
fo.close()
182+
else:
183+
# Yay, package
184+
is_package = True
172185
except (ImportError, IOError, SyntaxError):
173186
continue
174187
except UnicodeEncodeError:

0 commit comments

Comments
 (0)