1717console_locals = globals ().copy ()
1818
1919import code
20- import rlcompleter
2120import sys
2221
23- try :
24- import readline
25- except ImportError :
26- pass # readline is not available on all platforms
27-
28-
29- class DynamicCompleter (rlcompleter .Completer ):
30- """
31- A custom completer that dynamically updates its namespace to include new
32- imports made within the interactive session.
33- """
34- def __init__ (self , namespace ):
35- # Store a reference to the namespace, not a copy, so that changes to the namespace are
36- # reflected.
37- self .namespace = namespace
38-
39- def complete (self , text , state ):
40- # Update the completer's internal namespace with the current interactive session's locals
41- # and globals. This is the key to making new imports discoverable.
42- rlcompleter .Completer .__init__ (self , self .namespace )
43- return super ().complete (text , state )
44-
45-
4622if sys .stdin .isatty ():
4723 # Use the default options.
4824 exitmsg = None
@@ -52,8 +28,27 @@ def complete(self, text, state):
5228 sys .ps1 = ""
5329 sys .ps2 = ""
5430
55- if "readline" in globals ():
56- # Set up tab completion.
31+ # Set up tab completion.
32+ try :
33+ 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 )
51+
5752 completer = DynamicCompleter (console_locals )
5853 readline .set_completer (completer .complete )
5954
@@ -65,6 +60,8 @@ def complete(self, text, state):
6560 readline .parse_and_bind ("tab: complete" )
6661 else :
6762 print ("Could not enable tab completion!" )
63+ except ImportError :
64+ print ("Could not enable tab completion!" )
6865
6966# We set the banner to an empty string because the repl_template.py file already prints the banner.
7067code .interact (local = console_locals , banner = "" , exitmsg = exitmsg )
0 commit comments