1717console_locals = globals ().copy ()
1818
1919import code
20+ import rlcompleter
2021import sys
2122
23+
24+ class DynamicCompleter (rlcompleter .Completer ):
25+ """
26+ A custom completer that dynamically updates its namespace to include new
27+ imports made within the interactive session.
28+ """
29+
30+ def __init__ (self , namespace ):
31+ # Store a reference to the namespace, not a copy, so that changes to the namespace are
32+ # reflected.
33+ self .namespace = namespace
34+
35+ def complete (self , text , state ):
36+ # Update the completer's internal namespace with the current interactive session's locals
37+ # and globals. This is the key to making new imports discoverable.
38+ rlcompleter .Completer .__init__ (self , self .namespace )
39+ return super ().complete (text , state )
40+
41+
2242if sys .stdin .isatty ():
2343 # Use the default options.
2444 exitmsg = None
3151# Set up tab completion.
3252try :
3353 import readline
34- import rlcompleter
35-
36- class DynamicCompleter (rlcompleter .Completer ):
37- """
38- A custom completer that dynamically updates its namespace to include new
39- imports made within the interactive session.
40- """
41- def __init__ (self , namespace ):
42- # Store a reference to the namespace, not a copy, so that changes to the namespace are
43- # reflected.
44- self .namespace = namespace
45-
46- def complete (self , text , state ):
47- # Update the completer's internal namespace with the current interactive session's locals
48- # and globals. This is the key to making new imports discoverable.
49- rlcompleter .Completer .__init__ (self , self .namespace )
50- return super ().complete (text , state )
5154
5255 completer = DynamicCompleter (console_locals )
5356 readline .set_completer (completer .complete )
@@ -59,9 +62,15 @@ def complete(self, text, state):
5962 elif "GNU readline" in readline .__doc__ : # type: ignore
6063 readline .parse_and_bind ("tab: complete" )
6164 else :
62- print ("Could not enable tab completion!" )
65+ print (
66+ "Could not enable tab completion: "
67+ "unable to determine readline backend"
68+ )
6369except ImportError :
64- print ("Could not enable tab completion!" )
70+ print (
71+ "Could not enable tab completion: "
72+ "readline module not available on this platform"
73+ )
6574
6675# We set the banner to an empty string because the repl_template.py file already prints the banner.
6776code .interact (local = console_locals , banner = "" , exitmsg = exitmsg )
0 commit comments