Skip to content

Commit 5eb5205

Browse files
author
David Schäfer schaefed
committed
reduce the number of imports during initialization
1 parent d8eb65f commit 5eb5205

File tree

1 file changed

+25
-28
lines changed

1 file changed

+25
-28
lines changed

pyls/workspace.py

Lines changed: 25 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
# Copyright 2017 Palantir Technologies, Inc.
2+
from datetime import datetime
3+
24
import io
35
import logging
46
import os
@@ -17,22 +19,27 @@
1719
RE_END_WORD = re.compile('^[A-Za-z_0-9]*')
1820

1921

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]
22+
def get_submodules(modname):
23+
24+
submodules = []
25+
tovisit = [[modname, True]]
26+
27+
# imp.walk_packages actually imports packages imp.find_modules not,
28+
# so let's implement the recursion...
29+
while tovisit:
30+
mname, ispkg = tovisit.pop()
31+
try:
32+
_, mpath, _ = imp.find_module(mname) #, mpath)
33+
except ImportError:
34+
continue
35+
36+
submodules.append(mname)
37+
# if the curent module is not a package,
38+
# there is no need to continue the scan
39+
if ispkg:
40+
for mod in pkgutil.iter_modules([mpath], mname + "."):
41+
tovisit.append(mod[1:])
42+
3643
return submodules
3744

3845

@@ -48,19 +55,9 @@ def get_preferred_submodules():
4855
'strop', 'sys', 'thread', 'time', 'wx', 'xxsubtype',
4956
'zipimport', 'zlib', 'nose', 'os.path']
5057

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

6663

0 commit comments

Comments
 (0)