Skip to content

Commit 5f2d8d2

Browse files
David Schäfer schaefedschaefed
authored andcommitted
reduce the number of imports during initialization
1 parent d8eb65f commit 5f2d8d2

File tree

1 file changed

+27
-28
lines changed

1 file changed

+27
-28
lines changed

pyls/workspace.py

Lines changed: 27 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
# Copyright 2017 Palantir Technologies, Inc.
2+
23
import io
34
import logging
45
import os
@@ -17,22 +18,30 @@
1718
RE_END_WORD = re.compile('^[A-Za-z_0-9]*')
1819

1920

20-
def get_submodules(mod):
21-
"""Get all submodules of a given module"""
22-
def catch_exceptions(_module):
23-
pass
24-
25-
try:
26-
m = __import__(mod)
27-
submodules = [mod]
28-
submods = pkgutil.walk_packages(m.__path__, m.__name__ + '.', catch_exceptions)
29-
for sm in submods:
30-
sm_name = sm[1]
31-
submodules.append(sm_name)
32-
except ImportError:
33-
return []
34-
except: # pylint: disable=bare-except
35-
return [mod]
21+
def get_submodules(modname):
22+
23+
submodules = []
24+
tovisit = [[modname, True]]
25+
26+
# imp.walk_packages actually imports packages imp.find_modules not,
27+
# so let's implement the recursion...
28+
while tovisit:
29+
mname, ispkg = tovisit.pop()
30+
try:
31+
_, mpath, _ = imp.find_module(mname)
32+
# mimic python2 behaviour
33+
if not mpath:
34+
mpath = mname
35+
except ImportError:
36+
continue
37+
38+
submodules.append(mname)
39+
# if the curent module is not a package,
40+
# there is no need to continue the scan
41+
if ispkg:
42+
for mod in pkgutil.iter_modules([mpath], mname + "."):
43+
tovisit.append(mod[1:])
44+
3645
return submodules
3746

3847

@@ -48,19 +57,9 @@ def get_preferred_submodules():
4857
'strop', 'sys', 'thread', 'time', 'wx', 'xxsubtype',
4958
'zipimport', 'zlib', 'nose', 'os.path']
5059

51-
submodules = []
52-
for mod in mods:
53-
submods = get_submodules(mod)
54-
submodules += submods
55-
5660
actual = []
57-
for submod in submodules:
58-
try:
59-
imp.find_module(submod)
60-
actual.append(submod)
61-
except ImportError:
62-
pass
63-
61+
for mod in mods:
62+
actual.extend(get_submodules(mod))
6463
return actual
6564

6665

0 commit comments

Comments
 (0)