Skip to main content

Linting and formatting Python code in Google Colab.

Project description

colablinter

PyPI version License: MIT

Overview

colablinter is an IPython magic command extension designed specifically for Jupyter and Google Colab notebooks.

It integrates the high-speed linter ruff to perform code quality checks and enforce standards directly within Jupyter/Colab cells.

It allows developers to lint and format code on a cell-by-cell basis or check the entire notebook with simple commands.

Magic cell Commands

Command Type Description
%%cfix Cell Magic Fixes and Formats the current cell's code.
%%creport Cell Magic Displays a linting report for the current cell.
%clautofix Line Magic Activates or deactivates automatic code fixing and formatting before every cell execution.
%clreport Line Magic Displays a linting report for the entire saved notebook (requires Google Drive mount).
%%csql Cell Magic Formats SQL strings within the cell (e.g., query = """...""").

After executing a cell magic command, the fixed/reported code is immediately executed (if applicable), maintaining the notebook workflow.

Installation

Requires Python 3.10 or newer.

pip install colablinter

Usage

The extension must be explicitly loaded in the notebook session before use.

%load_ext colablinter
  1. Fix and Format cell (%%cfix)

    %%cfix corrects code and runs the formatter. The cell executes the fixed code.

    %%cfix
    import math, sys;
    
    class Example(   object ):
        def __init__    ( self, bar ):
          if bar : bar+=1;  bar=bar* bar   ; return bar
          else:
                        some_string = "foo"
                        return (sys.path, some_string)
    

    Fixed Cell:

    import math
    import sys
    
    
    class Example(object):
        def __init__(self, bar):
            if bar:
                bar += 1
                bar = bar * bar
                return bar
            else:
                some_string = "foo"
                return (sys.path, some_string)
    

    Note on F401 (Unused Imports): The linter is explicitly configured to ignore F401 errors (unused imports). This is to ensure compatibility with the stateful nature of Jupyter/Colab notebooks, where imports in one cell may be necessary for code execution in subsequent cells, preventing unintended breakage of the notebook's execution flow.

  2. Check cell quality (%%creport)

    Use %%creport to see linting reports for the code below the command.

    %%creport
    
    def invalid_code(x):
        return x + y # 'y' is not defined
    

    Output:

    [ColabLinter:INFO] F821 Undefined name `y`
    --> notebook_cell.py:2:16
    |
    1 | def invalid_code(x):
    2 |     return x + y # 'y' is not defined
    |                  ^
    |
    
    Found 1 error.
    

    Note: After the report is displayed, the code in the cell executes as normal. If errors exist (like F821), execution will fail.

  3. Activate/Deactivate Auto Fix (%clautofix)

    The %clautofix line magic allows you to automatically fix code before every code cell is executed.

    To Activate Auto Fixing:

    %clautofix on # %clautofix off when you want to deactivate
    
  4. Check entire notebook (%clreport)

    Use line magic %clreport to check across the entire saved notebook file (requires the notebook to be saved to Google Drive and mounted).

    %clreport /content/drive/MyDrive/Colab Notebooks/path/to/notebook.ipynb
    
  5. Format SQL strings (%%csql)

    The %%csql cell magic identifies a specific SQL string variable within the cell and automatically reformats it using SQLFluff. It enforces professional SQL standards, such as keyword capitalization and consistent indentation.

    %%csql some_query
    some_query = """
    select u.user_id, u.phone_number, u.email, count(o.order_id) as total_orders
    from users u join orders o on u.user_id = o.user_id
    where u.user_id is not null and u.status = 'active' and o.created_at >= '2025-01-01'
    group by u.user_id, u.phone_number, u.email
    order by total_orders desc
    """
    

    Fixed cell:

    some_query = """
    SELECT
        u.user_id,
        u.phone_number,
        u.email,
        count(o.order_id) AS total_orders
    FROM users AS u INNER JOIN orders AS o ON u.user_id = o.user_id
    WHERE
        u.user_id IS NOT NULL
        AND u.status = 'active'
        AND o.created_at >= '2025-01-01'
    GROUP BY u.user_id, u.phone_number, u.email
    ORDER BY total_orders DESC
    """
    

Known Caveats & Troubleshooting

Magic Command Execution: When using magic or terminal commands with %clautofix on active, the autofix mechanism is temporarily suppressed during the final execution step to prevent infinite loops or dual checks. If you want to disable auto-fixing, use %clautofix off

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

colablinter-0.1.6.tar.gz (9.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

colablinter-0.1.6-py3-none-any.whl (8.0 kB view details)

Uploaded Python 3

File details

Details for the file colablinter-0.1.6.tar.gz.

File metadata

  • Download URL: colablinter-0.1.6.tar.gz
  • Upload date:
  • Size: 9.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.9.18 {"installer":{"name":"uv","version":"0.9.18","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for colablinter-0.1.6.tar.gz
Algorithm Hash digest
SHA256 04410e0ea11a9a3211f56d6f6a5fa2f86ae2c99e8268a385c0670ca87be6dae6
MD5 1f10a565f85f930e6654d3a3ce197d61
BLAKE2b-256 178fcffb4ad8b45a57db89fcfc41cb63db113357ec79c1d60381a4d5ba09ca31

See more details on using hashes here.

File details

Details for the file colablinter-0.1.6-py3-none-any.whl.

File metadata

  • Download URL: colablinter-0.1.6-py3-none-any.whl
  • Upload date:
  • Size: 8.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.9.18 {"installer":{"name":"uv","version":"0.9.18","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for colablinter-0.1.6-py3-none-any.whl
Algorithm Hash digest
SHA256 359b6422b11b233612fa066091ee54119ec1d12aea00f773402363817c3d9192
MD5 d9d5b26fe9cc162486f430585218a5d0
BLAKE2b-256 66ee140753e84a94700ef4dd9177340cf72971e7fbef301053016cd5d50e47e4

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page