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.

docs: final google docs, add lint rules (#3226)

Myles Scolnicka77fe03f67d2
diff --git a/marimo/_ast/app.py b/marimo/_ast/app.py
index c9206c88bd..a460fd8af5 100644
--- a/marimo/_ast/app.py
+++ b/marimo/_ast/app.py
@@ -198,7 +198,7 @@ class App:
hide_code: bool = False,
**kwargs: Any,
) -> Cell | Callable[[Callable[..., Any]], Cell]:
- """A decorator to add a cell to the app
+ """A decorator to add a cell to the app.
This decorator can be called with or without parentheses. Each of the
following is valid:
@@ -218,9 +218,11 @@ class App:
```
Args:
- - func: The decorated function
- - disabled: Whether to disable the cell
- - kwargs: For forward-compatibility with future arguments
+ func: The decorated function.
+ column: The column number to place this cell in.
+ disabled: Whether to disable the cell.
+ hide_code: Whether to hide the cell's code.
+ **kwargs: For forward-compatibility with future arguments.
"""
del kwargs
diff --git a/marimo/_ast/cell.py b/marimo/_ast/cell.py
index 0992287805..e6570bd0b8 100644
--- a/marimo/_ast/cell.py
+++ b/marimo/_ast/cell.py
@@ -512,7 +512,7 @@ class Cell:
```
Args:
- **kwargs (Any):
+ **refs (Any):
You may pass values for any of this cell's references as keyword
arguments. marimo will automatically compute values for any refs
that are not provided by executing the parent cells that compute
diff --git a/marimo/_output/data/data.py b/marimo/_output/data/data.py
index 2217363919..cd1887450d 100644
--- a/marimo/_output/data/data.py
+++ b/marimo/_output/data/data.py
@@ -31,7 +31,8 @@ def image(data: bytes, ext: str = "png") -> VirtualFile:
"""Create a virtual file from an image.
Args:
- data: Image data in bytes
+ data (bytes): Image data in bytes
+ ext (str): File extension
Returns:
A `VirtualFile` object.
@@ -45,7 +46,8 @@ def audio(data: bytes, ext: str = "wav") -> VirtualFile:
"""Create a virtual file from audio.
Args:
- data: Audio data in bytes
+ data (bytes): Audio data in bytes
+ ext (str): File extension
Returns:
A `VirtualFile` object.
diff --git a/marimo/_output/formatting.py b/marimo/_output/formatting.py
index 675de14323..81896a1afa 100644
--- a/marimo/_output/formatting.py
+++ b/marimo/_output/formatting.py
@@ -310,23 +310,18 @@ def mime_to_html(mimetype: KnownMimeType, data: Any) -> Html:
@mddoc
def plain(value: Any) -> Plain:
- """
- Wrap a value to indicate that it should be displayed
- without any opinionated formatting.
-
- This is the best way to opt out of marimo's
- default dataframe rendering.
-
- **Example.**
+ """Wrap a value to indicate that it should be displayed without any opinionated formatting.
- ```python
- df = data.cars()
- mo.plain(df)
- ```
+ This is the best way to opt out of marimo's default dataframe rendering.
- **Args.**
+ Example:
+ ```python
+ df = data.cars()
+ mo.plain(df)
+ ```
- - `value`: Any value
+ Args:
+ value: Any value
"""
return Plain(value)
@@ -343,8 +338,7 @@ class Plain:
@mddoc
def iframe(html: str, *, width: str = "100%", height: str = "400px") -> Html:
- """
- Embed an HTML string in an iframe.
+ """Embed an HTML string in an iframe.
Scripts by default are not executed using `mo.as_html` or `mo.Html`,
so if you have a script tag (written as `<script></script>`),
@@ -354,16 +348,16 @@ def iframe(html: str, *, width: str = "100%", height: str = "400px") -> Html:
that may contain styles that could interfere with the rest of the
page.
- **Example.**
-
- ```python
- html = "<h1>Hello, world!</h1>"
- mo.iframe(html)
- ```
-
- **Args.**
+ Example:
+ ```python
+ html = "<h1>Hello, world!</h1>"
+ mo.iframe(html)
+ ```
- - `html`: An HTML string
+ Args:
+ html (str): An HTML string
+ width (str): The width of the iframe
+ height (str): The height of the iframe
"""
return Html(
diff --git a/marimo/_plugins/stateless/download.py b/marimo/_plugins/stateless/download.py
index 067f117e2f..993d80360d 100644
--- a/marimo/_plugins/stateless/download.py
+++ b/marimo/_plugins/stateless/download.py
@@ -28,13 +28,15 @@ def download(
Show a download button for a url, bytes, or file-like object.
Args:
- data: The data to download. Can be a string (interpreted as
+ data (Union[str, bytes, io.BytesIO]): The data to download. Can be a string (interpreted as
a URL), bytes, or a file opened in binary mode.
- filename: The name of the file to download.
+ filename (str): The name of the file to download.
If not provided, the name will be guessed from the data.
- mimetype: The mimetype of the file to download, for example,
+ mimetype (str): The mimetype of the file to download, for example,
(e.g. "text/csv", "image/png"). If not provided,
the mimetype will be guessed from the filename.
+ disabled (bool): Whether to disable the download button.
+ label (str): The label of the download button.
Returns:
An `Html` object for a download button.
diff --git a/marimo/_plugins/stateless/nav_menu.py b/marimo/_plugins/stateless/nav_menu.py
index e83fcd86f8..58025b44ea 100644
--- a/marimo/_plugins/stateless/nav_menu.py
+++ b/marimo/_plugins/stateless/nav_menu.py
@@ -26,6 +26,7 @@ def nav_menu(
menu: a dictionary of tab names to tab content;
the content can also be nested dictionaries (one level deep)
strings are interpreted as markdown
+ orientation (Literal["horizontal", "vertical"]): The orientation of the menu.
Returns:
An `Html` object.
diff --git a/marimo/_plugins/ui/_core/ui_element.py b/marimo/_plugins/ui/_core/ui_element.py
index 53c84fbe63..fa91dbf62a 100644
--- a/marimo/_plugins/ui/_core/ui_element.py
+++ b/marimo/_plugins/ui/_core/ui_element.py
@@ -354,61 +354,52 @@ class UIElement(Html, Generic[S, T], metaclass=abc.ABCMeta):
) -> form_plugin[S, T]:
"""Create a submittable form out of this `UIElement`.
- Use this method to create a form that gates the submission
- of a `UIElement`s value until a submit button is clicked.
-
- The value of the `form` is the value of the underlying
- element the last time the form was submitted.
-
- **Examples.**
-
- Convert any `UIElement` into a form:
-
- ```python
- prompt = mo.ui.text_area().form()
- ```
-
- Combine with `HTML.batch` to create a form made out of multiple
- `UIElements`:
-
- ```python
- form = (
- mo.ui.md(
- '''
- **Enter your prompt.**
-
- {prompt}
-
- **Choose a random seed.**
+ Creates a form that gates submission of a `UIElement`'s value until a submit button is clicked.
+ The form's value is the value of the underlying element from the last submission.
+
+ Examples:
+ Convert any `UIElement` into a form:
+ ```python
+ prompt = mo.ui.text_area().form()
+ ```
+
+ Combine with `HTML.batch` to create a form made out of multiple `UIElements`:
+ ```python
+ form = (
+ mo.ui.md(
+ '''
+ **Enter your prompt.**
+
+ {prompt}
+
+ **Choose a random seed.**
+
+ {seed}
+ '''
+ )
+ .batch(
+ prompt=mo.ui.text_area(),
+ seed=mo.ui.number(),
+ )
+ .form()
+ )
+ ```
- {seed}
- '''
- )
- .batch(
- prompt=mo.ui.text_area(),
- seed=mo.ui.number(),
- )
- .form()
- )
- ```
-
- **Args.**
-
- - `label`: A text label for the form.
- - `bordered`: whether the form should have a border
- - `loading`: whether the form should be in a loading state
- - `submit_button_label`: the label of the submit button
- - `submit_button_tooltip`: the tooltip of the submit button
- - `submit_button_disabled`: whether the submit button should be
- disabled
- - `clear_on_submit`: whether the form should clear its contents after
- submitting
- - `show_clear_button`: whether the form should show a clear button
- - `clear_button_label`: the label of the clear button
- - `clear_button_tooltip`: the tooltip of the clear button
- - `validate`: a function that takes the form's value and returns an
- error message if the value is invalid,
- or `None` if the value is valid
+ Args:
+ label: A text label for the form.
+ bordered: Whether the form should have a border.
+ loading: Whether the form should be in a loading state.
+ submit_button_label: The label of the submit button.
+ submit_button_tooltip: The tooltip of the submit button.
+ submit_button_disabled: Whether the submit button should be disabled.
+ clear_on_submit: Whether the form should clear its contents after submitting.
+ show_clear_button: Whether the form should show a clear button.
+ clear_button_label: The label of the clear button.
+ clear_button_tooltip: The tooltip of the clear button.
+ validate: A function that takes the form's value and returns an error message if invalid,
+ or `None` if valid.
+ on_change: A callback that takes the form's value and returns an error message if invalid,
+ or `None` if valid.
"""
from marimo._plugins.ui._impl.input import form as form_plugin
diff --git a/marimo/_runtime/complete.py b/marimo/_runtime/complete.py
index 207209a9b9..b613e5b17e 100644
--- a/marimo/_runtime/complete.py
+++ b/marimo/_runtime/complete.py
@@ -380,18 +380,17 @@ def complete(
and more comprehensive, but can only be carried out when the kernel
isn't executing or otherwise handling a request.
- **Args.**
-
- - `request`: the completion request
- - `graph`: dataflow graph backing the marimo program
- - `glbls`: global namespace
- - `glbls_lock`: lock protecting the global namespace, for interpreter-based
- completion
- - `stream`: Stream through which to communicate completion results
- - `docstrings_limit`: limit past which we won't attempt to fetch type hints
- and docstrings
- - `timeout`: timeout after which we'll stop fetching type hints/docstrings
- - `prefer_interpreter_completion`: whether to prefer interpreter completion
+ Args:
+ request: The completion request
+ graph: Dataflow graph backing the marimo program
+ glbls: Global namespace
+ glbls_lock: Lock protecting the global namespace, for interpreter-based
+ completion
+ stream: Stream through which to communicate completion results
+ docstrings_limit: Limit past which we won't attempt to fetch type hints
+ and docstrings
+ timeout: Timeout after which we'll stop fetching type hints/docstrings
+ prefer_interpreter_completion: Whether to prefer interpreter completion
"""
if not request.document.strip():
_write_no_completions(stream, request.id)
diff --git a/marimo/_runtime/redirect_streams.py b/marimo/_runtime/redirect_streams.py
index 93053bca33..ec67a2c870 100644
--- a/marimo/_runtime/redirect_streams.py
+++ b/marimo/_runtime/redirect_streams.py
@@ -24,7 +24,7 @@ def forward_os_stream(stream_object: Stdout | Stderr, fd: int) -> None:
def dup2newfd(fd: int) -> tuple[int, int, int]:
"""Create a pipe, with `fd` at the write end of it.
- Returns
+ Returns:
- duplicate (os.dup) of `fd`
- read end of pipe
- fd (which now points to the file referenced by the write end of the pipe)
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index 3584be4a61..a94138e0f1 100644
--- a/marimo/_runtime/runtime.py
+++ b/marimo/_runtime/runtime.py
@@ -921,7 +921,7 @@ class Kernel:
absent-mindedly redefine an existing name when creating a new cell:
such a mistake shouldn't invalidate the program state.
- Returns
+ Returns:
- set of cells that must be run to return kernel to consistent state
"""
LOGGER.debug("Mutating graph.")
diff --git a/marimo/_save/hash.py b/marimo/_save/hash.py
index d25350442b..5326e45145 100644
--- a/marimo/_save/hash.py
+++ b/marimo/_save/hash.py
@@ -274,50 +274,45 @@ class BlockHasher:
) -> None:
"""Hash the context of the module, and return a cache object.
- Hashing uses 3 combined methods: pure hashing, content addressed, and
- execution path:
-
- 1) "Pure" hashing is used when a block has no references. The hash is
- computed from the code itself.
-
- 2) "Content Addressed" hashing is used when all references are known
- and are shown to be primitive types (like a "pure" function).
-
- 3) "Execution Path" hashing is when objects may contain state or other
- hidden values that are difficult to hash deterministically. For this,
- the code used to produce the object is used as the basis of the hash.
- It follows that code which does not change, will produce the same
- output. This draws inspiration from hashing methods in Nix. One notable
- difference between these methods is that Nix sandboxes all execution,
- preventing external file access, and internet. Sources of
- non-determinism are not accounted for in this implementation, and are
- left to the user.
-
- In both cases, as long as the module is deterministic, the output will
- be deterministic. NB. The ContextExecutionPath is an extended case of
- ExecutionPath hashing, just utilizing additional context.
-
- For optimization, the content hash is performed after the execution
- cache- however the content references are collected first. This
- deferred content hash is useful in cases like repeated calls to a
- cached function.
+ Hashing uses 3 combined methods: pure hashing, content addressed, and execution path:
+
+ 1) "Pure" hashing is used when a block has no references. The hash is computed from the code
+ itself.
+
+ 2) "Content Addressed" hashing is used when all references are known and are shown to be
+ primitive types (like a "pure" function).
+
+ 3) "Execution Path" hashing is when objects may contain state or other hidden values that are
+ difficult to hash deterministically. For this, the code used to produce the object is used
+ as the basis of the hash. It follows that code which does not change, will produce the same
+ output. This draws inspiration from hashing methods in Nix. One notable difference between
+ these methods is that Nix sandboxes all execution, preventing external file access, and
+ internet. Sources of non-determinism are not accounted for in this implementation, and are
+ left to the user.
+
+ In both cases, as long as the module is deterministic, the output will be deterministic. NB.
+ The ContextExecutionPath is an extended case of ExecutionPath hashing, just utilizing
+ additional context.
+
+ For optimization, the content hash is performed after the execution cache- however the content
+ references are collected first. This deferred content hash is useful in cases like repeated
+ calls to a cached function.
Args:
- - module: The code content to create a hash for (e.g.
- for persistent_cache, the body of the `With` statement).
- - graph: The dataflow graph of the notebook.
- - cell_id: The cell id attached to the module.
- - scope: The definitions of (globals) available in execution context.
- - context: The "context" of the module, is a module corresponding
- additional execution context for the cell. For instance, in
- persistent_cache case, this applies to the code prior to
- invocation, but still in the same cell.
- - pin_modules: If True, then the module will be pinned to the version
- - hash_type: The type of hash to use.
- - apply_content_hash: If True, then the content hash will be
- attempted, otherwise only use execution path hash.
- - scoped_refs: A set of references that cannot be traced via
- execution path, and must be accounted for via content hashing.
+ module: The code content to create a hash for (e.g. for persistent_cache, the body of the
+ `With` statement).
+ graph: The dataflow graph of the notebook.
+ cell_id: The cell id attached to the module.
+ scope: The definitions of (globals) available in execution context.
+ context: The "context" of the module, is a module corresponding additional execution
+ context for the cell. For instance, in persistent_cache case, this applies to the code
+ prior to invocation, but still in the same cell.
+ pin_modules: If True, then the module will be pinned to the version
+ hash_type: The type of hash to use.
+ apply_content_hash: If True, then the content hash will be attempted, otherwise only use
+ execution path hash.
+ scoped_refs: A set of references that cannot be traced via execution path, and must be
+ accounted for via content hashing.
"""
# Hash should not be pinned to cell id
@@ -903,20 +898,22 @@ def content_cache_attempt_from_base(
as_fn: bool = False,
sensitive: bool = False,
) -> Cache:
- """Hash a code block with context from the same cell, and attempt a cache
- lookup.
+ """Hash a code block with context from the same cell, and attempt a cache lookup.
Args:
- - previous_block: The block to base the new block on.
- - scope: The scope of the new block.
- - loader: The loader to use for cache operations.
- - scoped_refs: A set of references that cannot be traced via
- execution path, and must be accounted for via content hashing.
- - as_fn: If True, then the block is treated as a function, and will not
- cache definitions in scope.
- - sensitive: If True, then the cache hash will to rehash references
- resolved with path execution. This will invalidate the cache more
- frequently.
+ previous_block: The block to base the new block on.
+ scope: The scope of the new block.
+ loader: The loader to use for cache operations.
+ scoped_refs: A set of references that cannot be traced via execution path, and must be
+ accounted for via content hashing.
+ required_refs: A set of references that must be present in the scope.
+ as_fn: If True, then the block is treated as a function, and will not cache definitions
+ in scope.
+ sensitive: If True, then the cache hash will to rehash references resolved with path
+ execution. This will invalidate the cache more frequently.
+
+ Returns:
+ A cache object that may, or may not be fully populated.
"""
if scoped_refs is None:
scoped_refs = set()
diff --git a/marimo/_server/asgi.py b/marimo/_server/asgi.py
index b9401866c1..08822c6a7c 100644
--- a/marimo/_server/asgi.py
+++ b/marimo/_server/asgi.py
@@ -38,42 +38,7 @@ class MiddlewareFactory(Protocol):
class ASGIAppBuilder(abc.ABC):
- """Class for building ASGI applications.
-
- Methods:
- with_app(
- path: str,
- root: str,
- middleware: Optional[list[MiddlewareFactory]] = None,
- ) -> ASGIAppBuilder:
- Adds a static application to the ASGI app at the specified path.
-
- Args:
- path (str): The URL path where the application will be mounted.
- root (str): The root directory of the application.
- middleware (Optional[list[MiddlewareFactory]]): Middleware to apply to the application.
-
- with_dynamic_directory(
- path: str,
- directory: str,
- validate_callback: Optional[ValidateCallback] = None,
- middleware: Optional[list[MiddlewareFactory]] = None,
- ) -> ASGIAppBuilder:
- Adds a dynamic directory to the ASGI app, allowing for dynamic loading of applications from the specified directory.
-
- Args:
- path (str): The URL path where the dynamic directory will be mounted.
- directory (str): The directory containing the applications.
- validate_callback (Optional[ValidateCallback]): A callback function to validate the application path.
- This is useful to plug in authentication or authorization checks.
- The validate_callback receives the application path and the scope,
- and returns a boolean indicating whether the application is valid.
- You may also raise an exception for a custom error message.
- middleware (Optional[list[MiddlewareFactory]]): Middleware to apply to sub app.
-
- build() -> ASGIApp:
- Builds and returns the final ASGI application.
- """
+ """Class for building ASGI applications."""
@abc.abstractmethod
def with_app(
diff --git a/marimo/_utils/dataclass_to_openapi.py b/marimo/_utils/dataclass_to_openapi.py
index 41aabe6283..5f1c75e88c 100644
--- a/marimo/_utils/dataclass_to_openapi.py
+++ b/marimo/_utils/dataclass_to_openapi.py
@@ -222,6 +222,7 @@ class PythonTypeToOpenAPI:
Args:
cls (Type[Any]): The dataclass to convert.
+ processed_classes (Dict[Any, str]): A dictionary of processed classes.
Raises:
ValueError: If cls is not a dataclass.
diff --git a/marimo/_utils/parse_dataclass.py b/marimo/_utils/parse_dataclass.py
index 7b23376838..45198ed335 100644
--- a/marimo/_utils/parse_dataclass.py
+++ b/marimo/_utils/parse_dataclass.py
@@ -139,19 +139,21 @@ def parse_raw(
) -> T:
"""Utility to parse a message as JSON, and instantiate into supplied type.
- `cls` must be a dataclass.
+ Args:
+ message: The message to parse
+ cls: The type to instantiate. Must be a dataclass.
+ allow_unknown_keys: Whether to allow unknown keys in the message.
- Supported collection types in the dataclass:
- - List, Tuple, Set, Dict
- - for Python 3.8 compatibility, must use collection types from
- the typing module (e.g., typing.List[int] instead of list[int])
+ Returns:
+ An instance of the supplied dataclass type.
- Transforms all fields in the parsed JSON from camel case to snake case.
+ Notes:
+ Supported collection types in the dataclass:
+ - List, Tuple, Set, Dict
+ - for Python 3.8 compatibility, must use collection types from
+ the typing module (e.g., `typing.List[int]` instead of `list[int]`)
- Args:
- ----
- message: the message to parse
- cls: the type to instantiate
+ Transforms all fields in the parsed JSON from camel case to snake case.
"""
# If it is a dict, it is already parsed and we can just build the
# dataclass.
diff --git a/pyproject.toml b/pyproject.toml
index 797e784f14..2e3bd5f388 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -287,6 +287,7 @@ ignore = [
# TODO: we should fix these, and enable this rule
"PT011", # `pytest.raises(ValueError)` is too broad, set the `match` parameter or use a more specific exception
"E501", # Line too long, we still trim
+ "D415", # First line should end with a period, question mark, or exclamation point
]
extend-select = [
# pyflakes
@@ -340,13 +341,24 @@ extend-select = [
"B019", # Use of functools.lru_cache or functools.cache on methods can lead to memory leaks
"TRY002", # Prohibit use of `raise Exception`, use specific exceptions instead.
"T201", # No print statements
+ "D3", # pydocstyle Quotes Issues
+ "D4", # pydocstyle Docstring Content Issues
+ "D207", # Docstring is under-indented
+ "D208", # Docstring is over-indented
+ "D210", # No whitespaces allowed surrounding docstring text
+ "D211", # No blank lines allowed before class docstring
+ "D214", # Section is over-indented
+ "D215", # Section underline is over-indented
]
# Never try to fix `F401` (unused imports).
unfixable = ["F401"]
+[tool.ruff.lint.pydocstyle]
+convention = "google"
+
[tool.ruff.lint.per-file-ignores]
-"**/{tests}/*" = ["ANN201", "ANN202", "T201"]
+"**/{tests}/*" = ["ANN201", "ANN202", "T201", "D"]
"dagger/*" = ["TID252"]
[tool.ruff.lint.isort]