Skip to content

Commit fadfaf9

Browse files
committed
gh-156363: Speed up import of rlcompleter by deferring inspect and re
rlcompleter imported inspect and re at module scope, but each is used in exactly one completion method (inspect in Completer._callable_postfix, re in Completer.attr_matches). Neither is needed to construct a Completer or set up interactive completion, only to compute completions. inspect in particular is a heavy import (it pulls in dis, tokenize, ...), so importing rlcompleter dropped from ~16.4ms to ~1.8ms of cumulative import time on a local build. Defer both imports into the methods that use them and add a lazy-import guard test.
1 parent a728080 commit fadfaf9

3 files changed

Lines changed: 12 additions & 2 deletions

File tree

Lib/rlcompleter.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,9 +31,7 @@
3131

3232
import atexit
3333
import builtins
34-
import inspect
3534
import keyword
36-
import re
3735
import __main__
3836
import warnings
3937
import types
@@ -105,6 +103,7 @@ def complete(self, text, state):
105103

106104
def _callable_postfix(self, val, word):
107105
if callable(val):
106+
import inspect
108107
word += "("
109108
try:
110109
if not inspect.signature(val).parameters:
@@ -153,6 +152,7 @@ def attr_matches(self, text):
153152
with a __getattr__ hook is evaluated.
154153
155154
"""
155+
import re
156156
m = re.match(r"(\w+(\.\w+)*)\.(\w*)", text)
157157
if not m:
158158
return []

Lib/test/test_rlcompleter.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import types
55
import rlcompleter
66
from test.support import MISSING_C_DOCSTRINGS
7+
from test.support.import_helper import ensure_lazy_imports
78

89
class CompleteMe:
910
""" Trivial class used in testing rlcompleter.Completer. """
@@ -252,5 +253,9 @@ def test_duplicate_globals(self):
252253
self.assertEqual(completer.complete('Ellipsis', 0), 'Ellipsis()')
253254
self.assertIsNone(completer.complete('Ellipsis', 1))
254255

256+
def test_lazy_imports(self):
257+
ensure_lazy_imports("rlcompleter", {"inspect", "re"})
258+
259+
255260
if __name__ == '__main__':
256261
unittest.main()
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
Speed up ``import rlcompleter`` by deferring the imports of :mod:`inspect`
2+
and :mod:`re` into the completion methods that use them. They are only
3+
needed while computing completions, so importing :mod:`rlcompleter` (for
4+
example when setting up interactive completion) no longer pays their import
5+
cost.

0 commit comments

Comments
 (0)