Skip to content
38 changes: 38 additions & 0 deletions python/bin/repl_stub.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,32 @@
console_locals = globals().copy()

import code
import rlcompleter
import sys

try:
import readline
except ImportError:
pass # readline is not available on all platforms


class DynamicCompleter(rlcompleter.Completer):
"""
A custom completer that dynamically updates its namespace to include new
imports made within the interactive session.
"""
def __init__(self, namespace):
# Store a reference to the namespace, not a copy, so that changes to the namespace are
# reflected.
self.namespace = namespace

def complete(self, text, state):
# Update the completer's internal namespace with the current interactive session's locals
# and globals. This is the key to making new imports discoverable.
rlcompleter.Completer.__init__(self, self.namespace)
return super().complete(text, state)


if sys.stdin.isatty():
# Use the default options.
exitmsg = None
Expand All @@ -28,5 +52,19 @@
sys.ps1 = ""
sys.ps2 = ""

if "readline" in globals():
# Set up tab completion.
completer = DynamicCompleter(console_locals)
readline.set_completer(completer.complete)

# TODO(jpwoodbu): Use readline.backend instead of readline.__doc__ once we can depend on having
# Python >=3.13.
if "libedit" in readline.__doc__: # type: ignore
readline.parse_and_bind("bind ^I rl_complete")
elif "GNU readline" in readline.__doc__: # type: ignore
readline.parse_and_bind("tab: complete")
else:
print("Could not enable tab completion!")

# We set the banner to an empty string because the repl_template.py file already prints the banner.
code.interact(local=console_locals, banner="", exitmsg=exitmsg)