Skip to content

About

Unified Python data access for Athena, Databricks, DuckDB and BigQuery

Topics

Resources

Code of conduct

Contributing

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

pydatalake

Supported Python versions PyPI CI License

Write one notebook, run it anywhere. pydatalake gives you a single DataFetcher API that queries AWS Athena locally and Spark SQL in Databricks — with automatic SQL dialect transpilation, narwhals DataFrames, and zero code changes between environments.


Quickstart

1. Install

pip install "pydatalake[local]"

The [local] extra installs all local runtime dependencies (Databricks + Athena + DuckDB + BigQuery). For smaller installs, see Install extras and choose a targeted extra. In Databricks notebooks, you don't need extras — pyspark is already available (pip install pydatalake).

Or install the CLI globally with pipx (no virtualenv needed):

pipx install 'pydatalake[local]'

See Install extras for all options.

2. First-time setup

The guided setup wizard configures both connections and saves them to ~/.pydatalake.toml:

pydatalake login                                  # interactive — configures both connections
pydatalake login --connection databricks          # Databricks only
pydatalake login --connection aws                 # AWS only
pydatalake login --host <databricks-url>          # go straight to a specific Databricks workspace

Databricks uses OAuth via the Databricks CLI. AWS credentials come from the standard boto3 chain — an AWS profile, SSO (aws sso login --profile <name>), environment variables, or an instance role; pydatalake login verifies them rather than logging you in.

Sharing config across a team. Write a presets file once and everyone can skip the prompts. No presets ship with the package, since hosts and accounts are deployment specific. Create ~/.pydatalake-teams.toml (or point PYDATALAKE_TEAMS_FILE at a shared copy):

[my-team.databricks]
host = "https://example.cloud.databricks.com"
profile = "pydatalake"
http_path = "/sql/1.0/warehouses/abc123"

[my-team.aws]
account_id = "000000000000"
role = "my_analyst_role"
pydatalake teams                 # list the presets you have defined
pydatalake login --team my-team  # apply one, no prompts

To share a preset with your team, commit your ~/.pydatalake-teams.toml somewhere they can reach and have them point PYDATALAKE_TEAMS_FILE at it.

3. Install agent skills

pydatalake install-skills

This installs the pydatalake-lib skill (the in-code Python API) and the pydatalake-cli skill (terminal/CLI surface) for both Claude Code and Cursor. For Cursor it also drops a small rule at .cursor/rules/pydatalake.mdc routing data tasks to pydatalake-cli. Skills auto-sync on every CLI invocation.

4. Your first query

from pydatalake import DataFetcher

fetcher = DataFetcher()
df = fetcher.sql("SELECT * FROM my_table")
print(df)

# Or query a table without writing SQL
df = fetcher.table("my_schema.my_table", columns=["id", "name"], status="active")
print(df)

# Or read raw parquet from S3 (no Hive/Glue catalog entry required)
from pydatalake import read_parquet

df = read_parquet("s3://my-bucket/exports/*.parquet", limit=1000)
print(df)

# When using DataFetcher, read_parquet is only available on the duckdb backend
duckdb_fetcher = DataFetcher(backend="duckdb")
df = duckdb_fetcher.read_parquet("s3://my-bucket/exports/*.parquet", limit=1000)

This works identically in your local IDE and in a Databricks notebook — no code changes needed.

5. PyCharm / DataGrip setup (optional)

cd into your project and run:

pydatalake jdbc-setup

By default this creates an Athena (pydatalake) entry in .idea/dataSources.xml pre-configured for your workgroup, AWS profile, and default catalog (AwsDataCatalog, or whatever data_source you have set under [athena] in ~/.pydatalake.toml). Unqualified queries like SELECT * FROM my_schema.my_table resolve against that catalog automatically — no need to prefix the catalog every time.

To generate a Databricks SQL datasource, run:

pydatalake jdbc-setup sqlwarehouse

This writes Databricks SQL (pydatalake) using [databricks_sql] config and embeds a short-lived token minted from your Databricks CLI profile. jdbc-setup auto-refreshes credentials before writing, so re-running the same command is enough after a token expires — no separate pydatalake auth step needed. After refreshing, delete the previous entry from your IDE's Database tool so old connections don't pile up.


How it works

pydatalake architecture

Default behavior

DataFetcher defaults to a Databricks SQL warehouse locally and Spark SQL in Databricks. SQL is written in Spark dialect by default (sql_dialect="spark") and auto-transpiled to the target engine via sqlglot.

Both return narwhals DataFrames with the same API.

Choosing a backend

Use the backend parameter to explicitly select an execution engine:

from pydatalake import DataFetcher

# Default — Databricks SQL warehouse locally, Spark in Databricks
fetcher = DataFetcher()

# Explicitly use Athena
fetcher = DataFetcher(backend="athena")

# Route queries to a remote Databricks cluster (uses ~/.pydatalake.toml config)
fetcher = DataFetcher(backend="sparkremote")

# Use a Databricks SQL warehouse (uses [databricks_sql] config section)
fetcher = DataFetcher(backend="sqlwarehouse")

# Query S3 directly via DuckDB (resolves tables through AWS Glue catalog)
fetcher = DataFetcher(backend="duckdb")

# Query Google BigQuery (local/IDE only)
fetcher = DataFetcher(backend="bigquery")

Note: In a Databricks environment, the backend parameter is always ignored — the native SparkBackend is used regardless. This means your code is portable: you can set backend="sqlwarehouse" for local development and it will silently do the right thing when the same notebook runs in Databricks.

backend= Local Databricks
"sqlwarehouse" (default) Databricks SQL warehouse Spark (native)
"athena" Athena Spark (always)
"sparkremote" Databricks remote cluster Spark (always)
"duckdb" DuckDB (reads S3 via Glue catalog) Spark (always)
"bigquery" Google BigQuery Spark (always) — see note
Backend instance That instance Spark (always)

The "sqlwarehouse" backend auto-reconnects on stale connections (e.g. "I/O operation on closed file"), retrying the query once on a fresh connection.

The "duckdb" backend resolves table names through the AWS Glue catalog and reads Parquet/Delta files directly from S3 using DuckDB — no Athena workgroup or Databricks cluster needed. It requires the [duckdb] or [local] extra and valid AWS credentials.

The "bigquery" backend queries Google BigQuery via the native google-cloud-bigquery client (the [bigquery] or [local] extra). Tables are BigQuery dataset.table refs (e.g. my_dataset.my_table). It is a local/IDE-only backend: BigQuery is a separate GCP data universe — there is no cross-cloud fallback, and inside a Databricks notebook the request falls through to Spark (which cannot reach CK data). Authenticate with pdl login -c bigquery (requires the gcloud CLI).

For advanced use, you can also pass a Backend instance directly:

from pydatalake.backends import AthenaBackend

backend = AthenaBackend(database="analytics", region="eu-west-1")
fetcher = DataFetcher(backend=backend)

Fallback backend

When a query fails with an access/permission error, pydatalake can automatically retry it on a fallback backend. By default, fallback_backend="athena" retries on Athena (disabled automatically if no Athena config exists). You can set it to any backend string, a Backend instance, or None to disable:

# Default — Athena fallback (auto-disabled if no athena config)
fetcher = DataFetcher()

# Use sparkremote as fallback
fetcher = DataFetcher(fallback_backend="sparkremote")

# Disable fallback
fetcher = DataFetcher(fallback_backend=None)

Configure the SQL warehouse with:

pydatalake config --server-hostname <host> --http-path <path>

PII guard

Queries returning cleartext sensitive data are refused for AI agent callers, so decrypted values do not land in an agent transcript. This covers DataFetcher, DataModifier, and the %%pdl_sql magic; it does not yet cover %%pdl_remote_sql, which executes on a remote Databricks session.

This is a safety control, not a security boundary — it prevents accidental exposure, not deliberate circumvention. See the user guide for details and the override.


Usage

For more examples, see the examples directory.

SQL dialect transpilation

By default, sql_dialect="spark" — pydatalake assumes your SQL is Spark SQL and transpiles it to the target engine's dialect automatically:

fetcher = DataFetcher()  # sql_dialect="spark" by default

# LATERAL VIEW EXPLODE → CROSS JOIN UNNEST, date_format patterns converted, etc.
df = fetcher.sql(
    """
    SELECT date_format(created_at, 'yyyy-MM-dd') AS dt,
           count(*) AS cnt
    FROM events
    LATERAL VIEW EXPLODE(tags) t AS tag
    WHERE created_at >= '2024-01-01'
    GROUP BY 1
"""
)

Conversely, if you prefer Trino SQL, set sql_dialect="trino". In Databricks, it's transpiled to Spark:

fetcher = DataFetcher(sql_dialect="trino")

# CROSS JOIN UNNEST → LATERAL VIEW EXPLODE, VARCHAR → STRING, etc.
df = fetcher.sql(
    """
    SELECT CAST(user_id AS VARCHAR), tag
    FROM events
    CROSS JOIN UNNEST(tags) AS t(tag)
"""
)

Random sampling

By default, LIMIT returns the first N rows scanned — typically in partition/file order, not a representative sample. Set random_sample=True to get a uniform random sample instead:

# Get 500 random rows (local/Athena only — ignored in Databricks)
df = fetcher.sql("SELECT * FROM events", limit=500, random_sample=True)

# Works with table() too
df = fetcher.table("my_schema.events", limit=500, random_sample=True)

Note: random_sample=True requires limit to be set. It wraps the query with ORDER BY RAND() LIMIT N, which is applied only locally (same scope as limit).

Column discovery

Get column names (and types) for any table, with automatic backend fallback:

fetcher = DataFetcher()

# Column names only
cols = fetcher.columns("my_schema.my_table")
# ['id', 'name', 'age', ...]

# Column names with types
cols = fetcher.columns("my_schema.my_table", include_types=True)
# [('id', 'bigint'), ('name', 'string'), ('age', 'int'), ...]

# Partition columns only
partition_cols = fetcher.partition_columns("my_schema.my_table")
# ['partition_date', 'tax_year']

Listing databases and tables

Discover what's available without knowing names up front. BigQuery only today — database maps to a BigQuery dataset:

fetcher = DataFetcher(backend="bigquery")

# Datasets in the configured project
dbs = fetcher.list_databases()
# ['analytics', 'my_dataset', ...]

# Tables within a dataset
tables = fetcher.list_tables("my_dataset")
# ['daily_mau', 'events', ...]

# Async variants
dbs = await fetcher.list_databases_async()
tables = await fetcher.list_tables_async("my_dataset")

Other backends raise NotImplementedError for these methods. Missing/expired ADC or denied access raises AuthenticationError (run pdl login -c bigquery).

Async queries

import asyncio
from pydatalake import DataFetcher


async def fetch_data():
    fetcher = DataFetcher()
    df = await fetcher.sql_async("SELECT * FROM customer_data")
    return df


df = asyncio.run(fetch_data())

Use table_async to query a table by name without writing SQL:

async def fetch_table():
    fetcher = DataFetcher()
    df = await fetcher.table_async(
        "my_schema.my_table", columns=["id", "name"], status="active"
    )
    return df

Multiple concurrent queries

import asyncio
from pydatalake import DataFetcher


async def fetch_multiple():
    fetcher = DataFetcher()

    queries = [
        "SELECT * FROM customers WHERE region = 'US'",
        "SELECT * FROM orders WHERE status = 'completed'",
        "SELECT * FROM products WHERE category = 'electronics'",
    ]

    tasks = [fetcher.sql_async(query) for query in queries]
    return await asyncio.gather(*tasks)


customers, orders, products = asyncio.run(fetch_multiple())

Custom Athena configuration

fetcher = DataFetcher(
    database="analytics_db",
    data_source="prod",
    workgroup="data_analysts",
    aws_profile="my-aws-profile",
)

df = fetcher.sql(
    query="SELECT customer_id, revenue FROM sales WHERE date >= '2024-01-01'",
    limit=5000,
)

Caching

Three caching layers are enabled by default for faster repeated queries (local only):

  • Disk cache (query_cache_seconds=300): stores results as parquet in /tmp, works with all backends
  • Client-side (athena_cache_seconds=300): awswrangler cache for Athena queries
  • Server-side (athena_result_reuse_minutes=60): Athena reuses previous execution results
# Defaults — all active, no config needed
fetcher = DataFetcher()

# Disable disk cache only
fetcher = DataFetcher(query_cache_seconds=None)

# Force a fresh fetch (clears disk cache, next query hits the backend)
fetcher.clear_cache()
df = fetcher.sql("SELECT * FROM my_table")

# Custom cache directory
fetcher = DataFetcher(query_cache_dir="/data/cache")

Authentication handling

from pydatalake import DataFetcher
from pydatalake.exceptions import AuthenticationError

# Automatic authentication (default — local/Athena only)
fetcher = DataFetcher(auto_auth=True)

try:
    df = fetcher.sql("SELECT * FROM my_table")
except AuthenticationError as e:
    print(f"Authentication failed: {e}")

# Manual authentication control
fetcher = DataFetcher(auto_auth=False)
fetcher.authenticate()
df = fetcher.sql("SELECT * FROM my_table")

DDL/DML operations

By default, DataFetcher only allows read-only queries (SELECT, DESCRIBE, SHOW, EXPLAIN), including set operations that combine SELECTs (UNION / UNION ALL / INTERSECT / EXCEPT). Mutation statements (CREATE, ALTER, DROP, INSERT, UPDATE, DELETE, etc.) raise a MutationNotAllowedError. This protects against accidental data modification, especially when queries are generated by AI agents.

For intentional DDL/DML operations, use DataModifier:

from pydatalake import DataModifier

modifier = DataModifier(backend="sqlwarehouse")
modifier.sql("CREATE TABLE my_schema.my_table (id INT, name STRING)")

DataModifier inherits all DataFetcher functionality (backend resolution, fallback, caching, transpilation) but skips the read-only validation.

Writing data

Write DataFrames to tables using DataWriter (Spark/Databricks only):

from pydatalake import DataWriter

writer = DataWriter(schema="analytics")
writer.write(df, "my_output_table", mode="overwrite")

Cross-environment utilities

Function Description
show(df) Display a DataFrame in the best format for the current environment
to_pandas(df) Convert any DataFrame type (narwhals, Spark, pandas) to pandas
count(df) Row count that works across all DataFrame types
Broadcast(obj) Broadcast variable — real sc.broadcast() in Databricks, passthrough locally
portable_udf(schema) Decorator: pandas_udf in Databricks, direct callable locally
portable_apply(df, udf, ...) Apply a portable UDF to a DataFrame in both environments
local_to_dbx(content) Convert local script content to Databricks notebook format
dbx_to_local(content) Convert Databricks notebook content to local format
from pydatalake import show, to_pandas, count

show(df)  # environment-aware display
pdf = to_pandas(df)  # always returns pandas.DataFrame
n = count(df)  # row count for any DataFrame type

Google Sheets I/O

  • Read from and write to Google Sheets via pdl.read_gsheet / pdl.to_gsheet (zero extra dependencies).
  • Auth is a one-time browser login that writes a Google OAuth token — see the Google Sheets I/O guide for setup.

Artifact Management

Upload and download files to/from S3:

from pydatalake import upload_artifact, download_artifact

s3_url = upload_artifact(
    s3_bucket="my-bucket",
    s3_object_key="models/my_model.pkl",
    local_path="./local_model.pkl",
)

local_path = download_artifact(
    s3_bucket="my-bucket",
    s3_object_key="models/my_model.pkl",
    local_path="./downloaded_model.pkl",  # Optional - creates temp file if not provided
)

CLI Reference

Tip: pdl is a shorthand alias for pydatalake. Subcommand aliases: q (query), cols (columns), cfg (config). Short flags: -b (--backend for query/columns), -c (--connection for login/auth), -d (--database). Example: pdl q "SELECT 1" -b athena

pydatalake version

Print the installed pydatalake version:

pydatalake version

pydatalake login

Authenticate with Databricks and AWS (both configured in one go by default):

pydatalake login                              # guided setup — configures both connections
pydatalake login --team <name>                # preset config + full auth (no prompts)
pydatalake login --connection databricks      # configure Databricks only
pydatalake login --auto                       # agents / headless — implies databricks, no prompts, in-context OAuth
pydatalake login --connection aws             # configure AWS only
pydatalake login --host <url>                 # skip prompts, go straight to Databricks
pydatalake login --profile <name>             # skip prompts, go straight to Databricks

--auto (Databricks only) skips all prompts and auto-selects the best cluster and SQL warehouse. It implies --connection databricks, so pydatalake login --auto is enough — no need to pass the connection explicitly. In a headless shell (AI agent / IDE) it uses the in-context OAuth flow instead of exiting, so agents can authenticate without a terminal. It cannot be combined with --team or --connection aws.

Without --host or --team, login resolves the Databricks workspace from the saved [databricks] config and prompts if there is none — it never assumes a workspace. Use pydatalake auth to refresh the currently-saved workspace in place.

--reset-profile repoints the Databricks profile's host in ~/.databrickscfg (or the file named by DATABRICKS_CONFIG_FILE). It is applied before authentication on every path, so it takes effect even when the token is still valid and no browser login is needed. Use it when login or auth reports that the profile points at a different workspace — the Databricks CLI refuses to authenticate while the profile's saved host and the requested host disagree, which is what a workspace URL change causes. Other keys in the profile are preserved and a backup is written to ~/.databrickscfg.bak.

Run pydatalake teams to see all available team presets.

pydatalake config

Manage settings stored in ~/.pydatalake.toml:

pydatalake config                                                    # view current config (default)
pydatalake config -c 0222-060058-j5mttouq --profile my-workspace    # save Databricks settings
pydatalake config --host <url>                                       # save workspace URL
pydatalake config --show                                             # same as no-arg default
pydatalake config --purge                                            # delete ~/.pydatalake.toml (with confirmation)
pydatalake config --purge --yes                                      # delete without confirmation

# SQL warehouse settings (saved to [databricks_sql] section)
pydatalake config --server-hostname <host> --http-path <path>
pydatalake config --sql-catalog my_catalog --sql-schema my_schema

# Athena settings (saved to [athena] section)
pydatalake config --database my_db --workgroup my_wg --data-source AwsDataCatalog
pydatalake config --aws-profile my-profile --region us-east-1
pydatalake config --aws-account-id 123456789 --aws-role my_role

pydatalake run

Execute a local Python file on a running Databricks cluster:

pydatalake run script.py                           # uses config for cluster & profile
pydatalake run script.py -c <cluster-id>           # override cluster ID
pydatalake run script.py --convert                 # convert local format before sending
pydatalake run script.py --timeout 300             # custom timeout (default: 600s)
pydatalake run script.py --host <url> --token <t>  # explicit auth (skip .databrickscfg)

Resolution order for cluster ID: --cluster-id flag → DATABRICKS_CLUSTER_ID env var → ~/.pydatalake.toml Resolution order for profile: --profile flag → ~/.pydatalake.toml

Requires the [dbx] or [local] extra: pip install "pydatalake[dbx]"

pydatalake shell

Start an interactive Python REPL whose every line runs on a Databricks cluster. State persists across lines, and a trailing bare expression echoes its repr() like the standard >>> prompt:

pydatalake shell                              # uses config for cluster & profile
pydatalake shell -c <cluster-id>              # connect by cluster ID
pydatalake shell --cluster-name "My Cluster"  # connect by name

Inside the shell, :help lists meta-commands, :local <code> runs a line in the local process, and :exit (or Ctrl-D) leaves. Requires the [local] or [notebook] extra (for prompt-toolkit).

pydatalake query

Run a SQL query and print results to stdout:

pydatalake query "SELECT * FROM my_table"
pydatalake query -f query.sql
pydatalake query "SELECT ..." --format json --limit 50
pydatalake query "SELECT ..." --database my_db
pydatalake query "SELECT ..." --sql-dialect spark
pydatalake query --backend athena "SELECT * FROM my_table"
Flag Default Description
query (positional) -- SQL string (mutually exclusive with -f)
-f / --file -- Read SQL from file
--format auto Output format: auto, csv, json, parquet, table, tsv. auto uses table in a terminal, csv when piped.
-o / --output -- Output file path (required for parquet format)
--limit 100 Max rows (0 for no limit)
--database default Database/schema override
--sql-dialect None spark or trino
--backend sqlwarehouse sqlwarehouse, sparkremote, athena, or duckdb
--workgroup config/default Athena workgroup (athena backend only)
--aws-profile config/default AWS profile (athena backend only)
--region config/default AWS region (athena backend only)
--data-source config/default Athena data source (athena backend only)
--timeout 600 Query timeout in seconds (sparkremote backend only; rejected for other backends)

Data goes to stdout (clean, parseable); errors go to stderr.

pydatalake columns

List column names (and optionally types) for a table. Defaults to SQL warehouse with automatic Athena fallback:

pydatalake columns schema.my_table
pydatalake columns schema.my_table --types
pydatalake columns schema.my_table --format json
pydatalake columns schema.my_table --backend athena
Flag Default Description
table (positional) -- Fully-qualified table name (schema.table)
--format auto Output format: auto, csv, json, table
--types False Include column data types
--backend sqlwarehouse sqlwarehouse, athena, sparkremote, or duckdb

pydatalake part-cols (alias: partition-columns)

List partition column names for a table. Backend defaults to auto, which prefers DuckDB/Glue metadata lookup when available, and otherwise falls back to SQL warehouse:

pydatalake part-cols schema.my_table
pydatalake part-cols schema.my_table --format json
pydatalake part-cols schema.my_table --backend duckdb
Flag Default Description
table (positional) -- Fully-qualified table name (schema.table)
--format auto Output format: auto, csv, json, table
--backend auto auto, sqlwarehouse, athena, sparkremote, or duckdb

pydatalake ls-tables (alias: list-tables)

List table names within a database. BigQuery only today — the dataset argument is a BigQuery dataset; other backends raise an error:

pydatalake ls-tables my_dataset
pydatalake ls-tables my_dataset --format json
Flag Default Description
dataset (positional) -- Database/dataset to list tables from (BigQuery dataset)
--format auto Output format: auto, csv, json, table
--backend bigquery BigQuery only today; other backends raise an error

pydatalake ls-databases (alias: list-databases)

List database/dataset names. BigQuery only today — lists datasets in the configured project; other backends raise an error:

pydatalake ls-databases
pydatalake ls-databases --format json
Flag Default Description
--format auto Output format: auto, csv, json, table
--backend bigquery BigQuery only today; other backends raise an error

pydatalake install-skills (alias: toggle-on)

Install pydatalake agent skills for Claude Code and/or Cursor. Claude Code receives pydatalake-lib; Cursor receives pydatalake-lib + pydatalake-cli:

pydatalake install-skills                      # install for both (global, default)
pydatalake install-skills --claude             # Claude Code only (pydatalake-lib)
pydatalake install-skills --cursor             # Cursor only (pydatalake-lib + pydatalake-cli)
pydatalake install-skills --scope project      # install into current directory
pydatalake toggle-on                           # same as install-skills

Skills are also auto-installed on every pydatalake CLI invocation when the target directories exist.

pydatalake uninstall-skills (alias: toggle-off)

Remove pydatalake agent skills from Claude Code and/or Cursor:

pydatalake uninstall-skills                    # remove from both (global, default)
pydatalake uninstall-skills --claude           # Claude Code only
pydatalake uninstall-skills --cursor           # Cursor only
pydatalake uninstall-skills --scope project    # remove from current directory
pydatalake toggle-off                          # same as uninstall-skills

Safe to run even if skills were never installed. To fully remove skills, also uninstall the package (skills auto-sync on every CLI invocation).

pydatalake jdbc-setup

Generate an IntelliJ-family (PyCharm, DataGrip, IntelliJ IDEA) Database-tool data source entry for your configured backend.

pydatalake jdbc-setup athena                   # Athena datasource (auto-refreshes AWS creds)
pydatalake jdbc-setup sqlwarehouse             # Databricks SQL datasource (auto-refreshes OAuth)
pydatalake jdbc-setup --dry-run                # print the XML without writing
pydatalake jdbc-setup --no-refresh             # skip the automatic credential refresh
pydatalake jdbc-setup --name "Athena prod"     # custom display name
pydatalake jdbc-setup -o path/to/dataSources.xml

Both backends refresh credentials automatically before writing, so refreshing an expired token is a single command — just re-run pydatalake jdbc-setup <backend>. After refreshing, delete the previous entry from your IDE's Database tool to avoid stale connections piling up. Use pydatalake status to see how long each backend's token has left.

Athena mode (backend=athena) reads [athena] from ~/.pydatalake.toml (region, AWS profile, workgroup, data_source) and merges an entry into dataSources.xml idempotently — re-running with the same config is a no-op. The driver's Catalog property is set to your configured data_source (default AwsDataCatalog), so unqualified SQL resolves against that catalog in the IDE.

Databricks mode (backend=sqlwarehouse) reads [databricks_sql] and writes a Databricks datasource that includes a short-lived access token from Databricks CLI.

Flag Default Notes
backend required athena or sqlwarehouse
-o, --output ./.idea/dataSources.xml Target XML file
--name backend-specific default Display name in the IDE
--no-refresh off Skip the automatic credential refresh before writing the datasource
--dry-run off Print XML, write nothing
--ide pycharm pycharm, intellij, or datagrip (all produce identical output)

Notebook conversion

Convert between local .py scripts (with # %% cell markers) and Databricks notebook format:

pydatalake to-dbx script.py              # convert local → Databricks (stdout)
pydatalake to-dbx script.py -o out.py    # convert local → Databricks (file)
pydatalake to-local notebook.py          # convert Databricks → local (stdout)
pydatalake to-local notebook.py -o out.py

Notebook magics

Install the notebook extra (pip install "pydatalake[notebook]"), then %load_ext pydatalake.

Run SQL and render the result inline — no connection needed:

%%pdl_sql df --backend athena --limit 100
SELECT id, name FROM analytics.users

Start the cell with a bare name (df above) to also bind the result locally as a pandas DataFrame.

Or run individual notebook cells on a Databricks cluster while keeping the rest local:

%pdl_connect cluster_id=0101-abc-xyz

%%pdl_remote -i df_local -o summary
summary = df_local.describe()
summary

-i ships local variables to the cluster, -o pulls remote ones back. A trailing matplotlib/seaborn figure renders inline in your notebook. See docs/user-guide/notebook-magics.md for the full guide.

AI assistant integration

In Claude Code, type /pydatalake for an interactive menu that guides you through querying, writing, setup, notebook conversion, remote notebook execution, and troubleshooting.


Installation Details

Poetry

poetry add pydatalake

pip (virtual environment)

python -m venv .venv
source .venv/bin/activate
pip install "pydatalake[local]"

Standalone CLI (pipx)

For users who only need the pydatalake CLI globally without managing a Python project:

pipx install 'pydatalake[local]'

Then authenticate and install agent skills:

pydatalake login             # authenticate with Databricks and AWS
pydatalake install-skills    # install Claude Code / Cursor skills

Upgrading:

pipx upgrade pydatalake

Note: The CLI checks for updates automatically every 24 hours and will notify you when a newer version is available. If you also have pydatalake in a project virtualenv, the venv version takes precedence when activated.

Install extras

Extra Use case Command
[local] Full local runtime (Databricks + Athena + DuckDB + BigQuery) pip install "pydatalake[local]"
[dbx] Databricks SQL warehouse/remote execution locally pip install "pydatalake[dbx]"
[athena] Athena backend locally pip install "pydatalake[athena]"
[duckdb] DuckDB backend locally (AWS Glue + S3) pip install "pydatalake[duckdb]"
[bigquery] BigQuery backend locally pip install "pydatalake[bigquery]"
(none) Databricks notebooks (pyspark built-in) pip install pydatalake

Local Development

This library uses Poetry to manage dependencies:

curl -sSL https://install.python-poetry.org | python3 - --version 2.1.3

For additional installation options, see the Poetry docs.

Publishing

Releases are tagged and published to PyPI by a maintainer. The version in pyproject.toml and the matching CHANGELOG.md entry are updated as part of each release.

Contributing

See Contribution Guidelines. The Roadmap lists planned work, including items marked contributor-friendly.

Support

License

Apache 2.0

About

Unified Python data access for Athena, Databricks, DuckDB and BigQuery

Topics

Resources

Code of conduct

Contributing

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages