Skip to content

Formatting: ruff line-length 100 + drop blank after short local imports - #6079

Merged
danielhanchen merged 2 commits into
mainfrom
studio-format-line-length-100
Jun 8, 2026
Merged

danielhanchen merged 2 commits into
mainfrom
studio-format-line-length-100

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

Two house-style tweaks to the Python auto-format pipeline, then the resulting
whole-repo reformat:

  • Raise ruff line-length from 88 to 100. Simple call / subscript /
    attribute-chain expressions that previously wrapped across three lines now sit
    on one line when they fit, e.g.

    # before
    EMBED_GGUF_REPO = os.environ.get(
        "RAG_EMBED_GGUF_REPO", "CompendiumLabs/bge-small-en-v1.5-gguf"
    )
    raise RuntimeError(
        f"embedder returned {len(items)} vectors for {len(chunk)} inputs"
    )
    if getattr(backend, "is_loaded", False) and getattr(
        backend, "is_vision", False
    ):
    
    # after
    EMBED_GGUF_REPO = os.environ.get("RAG_EMBED_GGUF_REPO", "CompendiumLabs/bge-small-en-v1.5-gguf")
    raise RuntimeError(f"embedder returned {len(items)} vectors for {len(chunk)} inputs")
    if getattr(backend, "is_loaded", False) and getattr(backend, "is_vision", False):

    E501 is not in the lint select set, so the linter is unaffected; only
    ruff format changes.

  • Drop the blank line after a short local import block. New
    remove_blank_after_short_import pass in scripts/enforce_kwargs_spacing.py:
    inside a small (<= 3 statement) indented suite, when a run of import /
    from ... import statements is followed only by blank lines and then another
    statement in the same suite, the blank lines are removed so the import sits
    next to the code that uses it, e.g.

    try:
        import torch
    
        return torch.inference_mode   # blank above is removed
    except Exception:
        from contextlib import nullcontext
    
        return nullcontext            # blank above is removed

    Module-level imports are left alone, a comment in the gap blocks the rule, and
    removing blank lines never changes the AST so it is always semantics-preserving.

Commits

  1. Config + the new import pass + tests/test_enforce_kwargs_spacing.py (small,
    reviewable).
  2. The mechanical whole-repo reformat (354 files, formatting-only).

The reformat is isolated in its own commit so it is trivially revertible.

Safety checks on the reformat

The 354-file reformat was gated before commit:

  • every changed file still parses (ast.parse);
  • ast.dump(before) == ast.dump(after) for every file with docstrings
    normalized: zero logic changes (in fact zero docstring-text changes too);
  • an independent checker (ast.dump via git, separate code path) reports
    354/354 unchanged code;
  • the pipeline is idempotent (a third pass is a no-op; ruff check is clean);
  • the runnable suites are identical before and after, per-test:
    studio/backend 2459 pass / 24 pre-existing fail / 48 skip (same tests),
    tests/security 37 pass, the new formatter tests 14 pass.

No files were hand-edited in the reformat commit.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request configures Ruff's line length to 100 in pyproject.toml and formats numerous Python files across the repository to adhere to this limit. Additionally, it introduces a new formatting rule in scripts/enforce_kwargs_spacing.py to remove blank lines after short import blocks in nested suites. The feedback suggests a performance optimization in this script by removing a redundant isinstance check on AST statement lists within the suites_of helper function.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment on lines +186 to +190
for attr in ("body", "orelse", "finalbody"):
val = getattr(node, attr, None)
if isinstance(val, list) and val and all(isinstance(s, ast.stmt) for s in val):
out.append(val)
return out

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

In suites_of, the check all(isinstance(s, ast.stmt) for s in val) is redundant and introduces an unnecessary $O(M)$ overhead (where $M$ is the number of statements in the suite) for every statement list in the AST. Since standard Python AST guarantees that body, orelse, and finalbody attributes on any non-Module node are always lists of ast.stmt (if they are lists at all), we can safely omit this check to improve performance, especially when processing large files.

Suggested change
for attr in ("body", "orelse", "finalbody"):
val = getattr(node, attr, None)
if isinstance(val, list) and val and all(isinstance(s, ast.stmt) for s in val):
out.append(val)
return out
for attr in ("body", "orelse", "finalbody"):
val = getattr(node, attr, None)
if isinstance(val, list) and val:
out.append(val)
return out
References
  1. To improve efficiency, avoid redundant data iterations. Combine checks and transformations into a single loop and return computed values for callers to reuse.

@danielhanchen
danielhanchen force-pushed the studio-format-line-length-100 branch 5 times, most recently from 45cc742 to f7aab9c Compare June 8, 2026 06:00

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f7aab9ce80

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

if t.type == tokenize.STRING:
pieces.append(("str", t.start, t.end, raw_of(t.start, t.end)))
i += 1
elif t.type == tokenize.FSTRING_START:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Guard f-string token constants on Python 3.11

The formatter now unconditionally references tokenize.FSTRING_START/FSTRING_END, but those token constants are only available in newer Python versions; this project still targets Python 3.11 (pyproject.toml sets target-version = "py311"). On a Python 3.11 pre-commit/CI environment, process_file() reaches merge_adjacent_string_literals() for every formatted file and crashes with AttributeError as soon as _string_pieces() evaluates this branch, so the formatting hook becomes unusable on a supported interpreter. Please fall back to treating f-strings as STRING tokens or guard these attributes with getattr.

Useful? React with 👍 / 👎.

…ter short local imports

Raise ruff line-length to 100 and extend the local pre-commit format pipeline.
Pre-ruff passes normalize def-signature magic commas (>= 3 params with a default
go one-per-line; everything else collapsible) and strip the magic trailing comma
from a short multi-line assert so ruff joins it onto one line (skipping asserts
with a comment, a one-element tuple, or whose one-line form would not fit).
Post-ruff passes pad kwarg '=', drop the blank line after a short local import
block, merge adjacent same-line string literals (a run mixing an f-string with a
plain string folds into one f-string, suppressed inside an assert that would not
then fit), and prune redundant pass statements. Every transform re-checks the
file AST and is dropped if it would differ. Mirror ruff's extend-exclude in the
local hook so it does not half-process skipped files.
… defaults, collapse short asserts

Apply the formatter pipeline (ruff format @ line-length 100 + the local
enforce_kwargs_spacing passes) across the repo. Verified AST-identical per file
(docstrings normalized), idempotent.
@danielhanchen
danielhanchen force-pushed the studio-format-line-length-100 branch from f7aab9c to 81d992f Compare June 8, 2026 10:48
@danielhanchen
danielhanchen merged commit 3ce187d into main Jun 8, 2026
64 checks passed
@danielhanchen
danielhanchen deleted the studio-format-line-length-100 branch June 8, 2026 11:24
Etherll added a commit to Etherll/unsloth that referenced this pull request Jun 11, 2026
Resolved conflict in unsloth/models/sentence_transformer.py: kept this
branch's functional rewrites in all 15 conflict hunks (upstream's side
was only the repo-wide comment-tightening/ruff-reflow passes unslothai#6079/unslothai#6095
applied to pre-rewrite code), while preserving upstream's auto-merged
cosmetic edits in non-conflicting regions via git merge-file --ours.

Co-Authored-By: Claude Fable 5 <[email protected]>
danielhanchen added a commit that referenced this pull request Sep 8, 2026
…he four files that drifted (#10512)

main is currently red under its own formatting hook. `pre-commit run --all-files`
reformats four files nobody is touching, so every open PR fails
`ruff-format-with-kwargs` with "files were modified by this hook" and a diff that
has nothing to do with it. #10494 is one; there will be more.

## Why the drift happens

`scripts/run_ruff_format.py` runs `sys.executable -m ruff`, which under
pre-commit is the pinned `ruff==0.6.9` and on a contributor's machine is whatever
they have. ruff's formatting is not stable across releases -- 0.9 moved the
wrapping in `assert cond, "msg"` from the condition to the message -- so a file
written under a newer ruff is committed in a style the hook reformats back, and
the hook then fails on it forever. The linter hook beside it is on v0.15.18 and
autoupdates, which makes a modern ruff the natural thing to have installed.

Nothing catches it locally: the file looks formatted, `ruff format --check`
agrees (with the newer ruff), and the failure only appears on pre-commit.ci.

## The change

`run_ruff_format.py` reads the pin out of `.pre-commit-config.yaml` and refuses,
before rewriting anything, when the ruff it would run is a different version. The
message names both versions and how to fix it, since "files were modified by this
hook" sends people looking for a defect in their own diff.
`UNSLOTH_RUFF_FORMAT_ANY_VERSION=1` overrides it, which a pin bump needs.

The pin is read rather than copied, so there is no second thing to forget; an
unreadable pin or an unreadable ruff is not a mismatch, because the format step
below already fails loudly on its own.

## The four files

Re-formatted with the pinned 0.6.9, no other change: the assert wrapping in
`test_docker_studio_keep_cuda_prebuilt.py`, `test_password_prompt_backstop.py`
and `test_studio_password_prompt.py`, and the blank line after a short local
import in `unsloth_cli/commands/studio.py`, which is the repo's own rule from
#6079.

Not a pin bump: moving to 0.16 reformats 1062 files and would conflict with every
open PR. That is worth doing deliberately, on a quiet branch, not as a side
effect of unblocking CI.

15 new tests, and the existing kwarg-spacing suite still passes (77 total).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant