Skip to content

Commit f27e7bc

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

File tree

1 file changed

+28
-28
lines changed

1 file changed

+28
-28
lines changed

pyls/workspace.py

Lines changed: 28 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,30 @@
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)
33+
# mimic python2 behaviour
34+
if not mpath:
35+
mpath = mname
36+
except ImportError:
37+
continue
38+
39+
submodules.append(mname)
40+
# if the curent module is not a package,
41+
# there is no need to continue the scan
42+
if ispkg:
43+
for mod in pkgutil.iter_modules([mpath], mname + "."):
44+
tovisit.append(mod[1:])
45+
3646
return submodules
3747

3848

@@ -48,19 +58,9 @@ def get_preferred_submodules():
4858
'strop', 'sys', 'thread', 'time', 'wx', 'xxsubtype',
4959
'zipimport', 'zlib', 'nose', 'os.path']
5060

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

6666

0 commit comments

Comments
 (0)