Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

feat: add `basedpyright` (#5712)

Winston H.96e18ea3ad24
diff --git a/frontend/src/components/app-config/user-config-form.tsx b/frontend/src/components/app-config/user-config-form.tsx
index 8715db8a75..7636924e90 100644
--- a/frontend/src/components/app-config/user-config-form.tsx
+++ b/frontend/src/components/app-config/user-config-form.tsx
@@ -484,6 +484,49 @@ export const UserConfigForm: React.FC = () => {
</div>
)}
/>
+ <FormField
+ control={form.control}
+ name="language_servers.basedpyright.enabled"
+ render={({ field }) => (
+ <div className="flex flex-col gap-1">
+ <FormItem className={formItemClasses}>
+ <FormLabel>
+ <Badge variant="defaultOutline" className="mr-2">
+ Beta
+ </Badge>
+ basedpyright (
+ <ExternalLink href="https://github.com/DetachHead/basedpyright">
+ docs
+ </ExternalLink>
+ )
+ </FormLabel>
+ <FormControl>
+ <Checkbox
+ data-testid="basedpyright-checkbox"
+ checked={field.value}
+ disabled={field.disabled}
+ onCheckedChange={(checked) => {
+ field.onChange(Boolean(checked));
+ }}
+ />
+ </FormControl>
+ <FormMessage />
+ <IsOverridden
+ userConfig={config}
+ name="language_servers.basedpyright.enabled"
+ />
+ </FormItem>
+ {field.value && !capabilities.basedpyright && (
+ <Banner kind="danger">
+ basedpyright is not available in your current
+ environment. Please install{" "}
+ <Kbd className="inline">basedpyright</Kbd> in your
+ environment.
+ </Banner>
+ )}
+ </div>
+ )}
+ />
<FormField
control={form.control}
name="language_servers.ty.enabled"
diff --git a/frontend/src/core/codemirror/language/languages/python.ts b/frontend/src/core/codemirror/language/languages/python.ts
index 40ad68fd7a..9da0658ece 100644
--- a/frontend/src/core/codemirror/language/languages/python.ts
+++ b/frontend/src/core/codemirror/language/languages/python.ts
@@ -153,6 +153,24 @@ const tyLspClient = once((_: LSPConfig) => {
);
});
+const pyrightClient = once((_: LSPConfig) => {
+ const lspClientOpts = {
+ transport: createTransport("basedpyright"),
+ rootUri: getLSPDocumentRootUri(),
+ workspaceFolders: [],
+ };
+
+ // We wrap the client in a NotebookLanguageServerClient to add some
+ // additional functionality to handle multiple cells
+ return new NotebookLanguageServerClient(
+ new LanguageServerClient({
+ ...lspClientOpts,
+ autoClose: false,
+ }),
+ {},
+ );
+});
+
/**
* Language adapter for Python.
*/
@@ -209,6 +227,9 @@ export class PythonLanguageAdapter implements LanguageAdapter<{}> {
if (lspConfig?.ty?.enabled && hasCapability("ty")) {
clients.push(tyLspClient(lspConfig));
}
+ if (lspConfig?.basedpyright?.enabled && hasCapability("basedpyright")) {
+ clients.push(pyrightClient(lspConfig));
+ }
if (clients.length > 0) {
const client =
diff --git a/frontend/src/core/codemirror/lsp/transports.ts b/frontend/src/core/codemirror/lsp/transports.ts
index 87998e83f8..b539cda89b 100644
--- a/frontend/src/core/codemirror/lsp/transports.ts
+++ b/frontend/src/core/codemirror/lsp/transports.ts
@@ -12,7 +12,9 @@ import { getRuntimeManager } from "../../runtime/config";
* @param serverName - The name of the LSP server.
* @returns The transport.
*/
-export function createTransport(serverName: "pylsp" | "copilot" | "ty") {
+export function createTransport(
+ serverName: "pylsp" | "basedpyright" | "copilot" | "ty",
+) {
const runtimeManager = getRuntimeManager();
const transport = new WebSocketTransport(
runtimeManager.getLSPURL(serverName).toString(),
diff --git a/frontend/src/core/config/capabilities.ts b/frontend/src/core/config/capabilities.ts
index 5d87102f70..c046149eb3 100644
--- a/frontend/src/core/config/capabilities.ts
+++ b/frontend/src/core/config/capabilities.ts
@@ -6,6 +6,7 @@ import { store } from "../state/jotai";
export const capabilitiesAtom = atom<Capabilities>({
terminal: false,
pylsp: false,
+ basedpyright: false,
ty: false,
});
diff --git a/frontend/src/core/runtime/runtime.ts b/frontend/src/core/runtime/runtime.ts
index 40ee2ab5ed..01216b6fd5 100644
--- a/frontend/src/core/runtime/runtime.ts
+++ b/frontend/src/core/runtime/runtime.ts
@@ -135,7 +135,7 @@ export class RuntimeManager {
/**
* The URL of the copilot server.
*/
- getLSPURL(lsp: "pylsp" | "copilot" | "ty"): URL {
+ getLSPURL(lsp: "pylsp" | "basedpyright" | "copilot" | "ty"): URL {
if (lsp === "copilot") {
// For copilot, don't include any query parameters
const url = this.formatWsURL(`/lsp/${lsp}`);
diff --git a/marimo/_config/config.py b/marimo/_config/config.py
index 960136fa59..00484fd27b 100644
--- a/marimo/_config/config.py
+++ b/marimo/_config/config.py
@@ -339,6 +339,18 @@ class PythonLanguageServerConfig(TypedDict, total=False):
enable_pyflakes: bool
+@dataclass
+class BasedpyrightServerConfig(TypedDict, total=False):
+ """
+ Configuration options for basedpyright Language Server.
+
+ basedpyright handles completion, hover, go-to-definition, and diagnostics,
+ but we only use it for diagnostics.
+ """
+
+ enabled: bool
+
+
@dataclass
class TyLanguageServerConfig(TypedDict, total=False):
"""
@@ -361,6 +373,7 @@ class LanguageServersConfig(TypedDict, total=False):
"""
pylsp: PythonLanguageServerConfig
+ basedpyright: BasedpyrightServerConfig
ty: TyLanguageServerConfig
diff --git a/marimo/_dependencies/dependencies.py b/marimo/_dependencies/dependencies.py
index e7d822e77e..10aad7c5d7 100644
--- a/marimo/_dependencies/dependencies.py
+++ b/marimo/_dependencies/dependencies.py
@@ -222,6 +222,7 @@ class DependencyManager:
panel = Dependency("panel")
sqlalchemy = Dependency("sqlalchemy")
pylsp = Dependency("pylsp")
+ basedpyright = Dependency("basedpyright")
ty = Dependency("ty")
pytest = Dependency("pytest")
vegafusion = Dependency("vegafusion")
diff --git a/marimo/_messaging/ops.py b/marimo/_messaging/ops.py
index c530b69cbf..fd7ce8928d 100644
--- a/marimo/_messaging/ops.py
+++ b/marimo/_messaging/ops.py
@@ -419,11 +419,13 @@ class KernelCapabilities:
terminal: bool = False
pylsp: bool = False
ty: bool = False
+ basedpyright: bool = False
def __post_init__(self) -> None:
# Only available in mac/linux
self.terminal = not is_windows() and not is_pyodide()
self.pylsp = DependencyManager.pylsp.has()
+ self.basedpyright = DependencyManager.basedpyright.has()
self.ty = DependencyManager.ty.has()
diff --git a/marimo/_server/lsp.py b/marimo/_server/lsp.py
index 070d4cc03f..8786268253 100644
--- a/marimo/_server/lsp.py
+++ b/marimo/_server/lsp.py
@@ -226,6 +226,48 @@ class PyLspServer(BaseLspServer):
)
+class BasedpyrightServer(BaseLspServer):
+ id = "basedpyright"
+
+ def start(self) -> Optional[Alert]:
+ # basedpyright is not required, so we don't want to alert or fail if it is not installed
+ if not DependencyManager.basedpyright.has():
+ LOGGER.debug("basedpyright is not installed. Skipping LSP server.")
+ return None
+ return super().start()
+
+ def validate_requirements(self) -> Union[str, Literal[True]]:
+ if not DependencyManager.basedpyright.has():
+ return "basedpyright is missing. Install it with `pip install basedpyright`."
+
+ if not DependencyManager.which("node"):
+ return "node.js binary is missing. Install node at https://nodejs.org/."
+
+ return True
+
+ def get_command(self) -> list[str]:
+ lsp_bin = marimo_package_path() / "_lsp" / "index.cjs"
+ log_file = _loggers.get_log_directory() / "basedpyright-lsp.log"
+
+ return [
+ "node",
+ str(lsp_bin),
+ "--port",
+ str(self.port),
+ "--lsp",
+ "basedpyright-langserver --stdio",
+ "--log-file",
+ str(log_file),
+ ]
+
+ def missing_binary_alert(self) -> Alert:
+ return Alert(
+ title="basedpyright: Connection Error",
+ description="<span><a class='hyperlink' href='https://docs.basedpyright.com'>Install basedpyright</a> for type checking support.</span>",
+ variant="danger",
+ )
+
+
class TyServer(BaseLspServer):
id = "ty"
@@ -284,6 +326,7 @@ class NoopLspServer(LspServer):
class CompositeLspServer(LspServer):
LANGUAGE_SERVERS = {
"pylsp": PyLspServer,
+ "basedpyright": BasedpyrightServer,
"ty": TyServer,
"copilot": CopilotLspServer,
}
diff --git a/packages/openapi/api.yaml b/packages/openapi/api.yaml
index fdc2dee21d..854e002679 100644
--- a/packages/openapi/api.yaml
+++ b/packages/openapi/api.yaml
@@ -1280,6 +1280,8 @@ components:
type: object
capabilities:
properties:
+ basedpyright:
+ type: boolean
pylsp:
type: boolean
terminal:
@@ -1290,6 +1292,7 @@ components:
- terminal
- pylsp
- ty
+ - basedpyright
type: object
cell_ids:
items:
@@ -1638,6 +1641,11 @@ components:
type: object
language_servers:
properties:
+ basedpyright:
+ properties:
+ enabled:
+ type: boolean
+ type: object
pylsp:
properties:
enable_flake8:
@@ -2741,7 +2749,7 @@ components:
type: object
info:
title: marimo API
- version: 0.14.13
+ version: 0.14.15
openapi: 3.1.0
paths:
/@file/{filename_and_length}:
diff --git a/packages/openapi/src/api.ts b/packages/openapi/src/api.ts
index 0ee3bd9af7..987ea8a510 100644
--- a/packages/openapi/src/api.ts
+++ b/packages/openapi/src/api.ts
@@ -3063,6 +3063,7 @@ export interface components {
width: "normal" | "compact" | "medium" | "full" | "columns";
};
capabilities: {
+ basedpyright: boolean;
pylsp: boolean;
terminal: boolean;
ty: boolean;
@@ -3231,6 +3232,9 @@ export interface components {
vimrc?: string | null;
};
language_servers?: {
+ basedpyright?: {
+ enabled?: boolean;
+ };
pylsp?: {
enable_flake8?: boolean;
enable_mypy?: boolean;
diff --git a/tests/_server/test_lsp.py b/tests/_server/test_lsp.py
index c0da9a2fc8..14103ef804 100644
--- a/tests/_server/test_lsp.py
+++ b/tests/_server/test_lsp.py
@@ -149,9 +149,13 @@ def test_composite_server():
with mock.patch("marimo._server.lsp.DependencyManager") as mock_dm:
mock_dm.pylsp = mock.MagicMock()
mock_dm.pylsp.has.return_value = True
- total_lsp_servers = 3
+ total_lsp_servers = 4
config = LanguageServersConfig(
- {"pylsp": {"enabled": True}, "ty": {"enabled": True}}
+ {
+ "pylsp": {"enabled": True},
+ "ty": {"enabled": True},
+ "basedpyright": {"enabled": True},
+ }
)
completion_config = CompletionConfig(
{"copilot": True, "activate_on_typing": True}
@@ -164,6 +168,7 @@ def test_composite_server():
assert server._is_enabled("pylsp") is True
assert server._is_enabled("copilot") is True
assert server._is_enabled("ty") is True
+ assert server._is_enabled("basedpyright") is True
# Test with only pylsp
config = LanguageServersConfig({"pylsp": {"enabled": True}})
@@ -179,7 +184,11 @@ def test_composite_server():
# Test with only ty enabled
config = LanguageServersConfig(
- {"ty": {"enabled": True}, "pylsp": {"enabled": False}}
+ {
+ "ty": {"enabled": True},
+ "pylsp": {"enabled": False},
+ "basedpyright": {"enabled": False},
+ }
)
completion_config = CompletionConfig(
{"copilot": False, "activate_on_typing": True}
@@ -188,9 +197,29 @@ def test_composite_server():
server = CompositeLspServer(config_reader, min_port=8000)
assert len(server.servers) == total_lsp_servers
assert server._is_enabled("pylsp") is False
+ assert server._is_enabled("basedpyright") is False
assert server._is_enabled("copilot") is False
assert server._is_enabled("ty") is True
+ # Test with only basedpyright enabled
+ config = LanguageServersConfig(
+ {
+ "basedpyright": {"enabled": True},
+ "pylsp": {"enabled": False},
+ "ty": {"enabled": False},
+ }
+ )
+ completion_config = CompletionConfig(
+ {"copilot": False, "activate_on_typing": True}
+ )
+ config_reader = as_reader(completion_config, config)
+ server = CompositeLspServer(config_reader, min_port=8000)
+ assert len(server.servers) == total_lsp_servers
+ assert server._is_enabled("pylsp") is False
+ assert server._is_enabled("basedpyright") is True
+ assert server._is_enabled("copilot") is False
+ assert server._is_enabled("ty") is False
+
# Test with nothing enabled
config = LanguageServersConfig({"pylsp": {"enabled": False}})
completion_config = CompletionConfig(