Skip to content

feat: Add support for REPLs #2723

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 16 commits into
base: main
Choose a base branch
from
33 changes: 33 additions & 0 deletions python/bin/BUILD.bazel
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
load("//python/private:interpreter.bzl", _interpreter_binary = "interpreter_binary")
load("//python/private:repl.bzl", "py_repl_binary")

filegroup(
name = "distribution",
Expand All @@ -22,3 +23,35 @@ label_flag(
name = "python_src",
build_setting_default = "//python:none",
)

py_repl_binary(
name = "repl",
stub = ":repl_stub",
visibility = ["//visibility:public"],
deps = [
":repl_dep",
":repl_stub_dep",
],
)

# The user can replace this with their own stub. E.g. they can use this to
# import ipython instead of the default shell.
label_flag(
name = "repl_stub",
build_setting_default = "repl_stub.py",
)

# The user can modify this flag to make an interpreter shell library available
# for the stub. E.g. if they switch the stub for an ipython-based one, then they
# can point this at their version of ipython.
label_flag(
name = "repl_stub_dep",
build_setting_default = "//python/private:empty",
)

# The user can modify this flag to make arbitrary PyInfo targets available for
# import on the REPL.
label_flag(
name = "repl_dep",
build_setting_default = "//python/private:empty",
)
3 changes: 3 additions & 0 deletions python/bin/repl_stub.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import code

code.interact()
4 changes: 4 additions & 0 deletions python/private/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -798,6 +798,10 @@ current_interpreter_executable(
visibility = ["//visibility:public"],
)

py_library(
name = "empty",
)

sentinel(
name = "sentinel",
)
67 changes: 67 additions & 0 deletions python/private/repl.bzl
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
# Copyright 2025 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Implementation of the rules to expose a REPL."""

load("//python:py_binary.bzl", "py_binary")

def _generate_repl_main_impl(ctx):
stub_repo = ctx.attr.stub.label.repo_name or ctx.workspace_name
stub_path = "/".join([stub_repo, ctx.file.stub.short_path])

ctx.actions.expand_template(
template = ctx.file._template,
output = ctx.outputs.out,
substitutions = {
"%stub_path%": stub_path,
},
)

_generate_repl_main = rule(
implementation = _generate_repl_main_impl,
attrs = {
"out": attr.output(
mandatory = True,
),
"stub": attr.label(
mandatory = True,
allow_single_file = True,
),
"_template": attr.label(
default = "//python/private:repl_template.py",
allow_single_file = True,
),
},
)

def py_repl_binary(name, stub, deps = [], data = [], **kwargs):
_generate_repl_main(
name = "%s_py" % name,
stub = stub,
out = "%s.py" % name,
)

py_binary(
name = name,
srcs = [
":%s.py" % name,
],
data = data + [
stub,
],
deps = deps + [
"//python/runfiles",
],
**kwargs
)
28 changes: 28 additions & 0 deletions python/private/repl_template.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import os
import runpy
from pathlib import Path

from python.runfiles import runfiles

STUB_PATH = "%stub_path%"


def start_repl():
# Simulate Python's behavior when a valid startup script is defined by the
# PYTHONSTARTUP variable. If this file path fails to load, print the error
# and revert to the default behavior.
if startup_file := os.getenv("PYTHONSTARTUP"):
try:
source_code = Path(startup_file).read_text()
except Exception as error:
print(f"{type(error).__name__}: {error}")
else:
compiled_code = compile(source_code, filename=startup_file, mode="exec")
eval(compiled_code, {})

bazel_runfiles = runfiles.Create()
runpy.run_path(bazel_runfiles.Rlocation(STUB_PATH), run_name="__main__")


if __name__ == "__main__":
start_repl()