Type Checking a One-Off Script with ty
ty 1.0 came out on the 1st December. I’ve used mypy and Pyright before, but only on projects with a pyproject.toml, a virtual environment and a CI job to run them. The scripts I write to answer one question never get type checked, and they’re exactly where a silly mistake goes unnoticed until it bites.
This release has something for them. In preview, ty can read a PEP 723 script’s dependency list (a comment block at the top of the file), ask uv to build an environment from it and check the script against that, with no project or virtual environment to keep around. So I wrote a quick script the way I normally would, over GPS tracks from two walks this year, and pointed ty at it.
Everything here was run with ty 1.0.0, uv 0.13.12, Python 3.13.8, Polars 2.2.0 and DuckDB 2.0.1. ty 1.1.0 came out on the 3rd December and gives identical diagnostics for everything below. Script support is marked as preview, so expect details to change.
The script
The question was how my times compare with Naismith’s rule, the old hillwalking rule of thumb: an hour for every 5 km, plus an hour for every 600 m of ascent. The data is the GPX export from Garmin Connect for the east ridge of Beinn a’ Chaorainn in February and Yr Wyddfa via the Watkin Path in March. Each track point has a position, an elevation and a timestamp, and a Garmin extension adds heart rate.
This is the first version, written quickly and run once:
# /// script
# requires-python = ">=3.13"
# dependencies = ["polars==2.2.0", "duckdb==2.0.1", "pyarrow"]
# ///
import sys
import xml.etree.ElementTree as ET
from datetime import datetime
from pathlib import Path
from typing import TypedDict
import duckdb
import polars as pl
NS = {
"gpx": "http://www.topografix.com/GPX/1/1",
"tpx": "http://www.garmin.com/xmlschemas/TrackPointExtension/v1",
}
class TrackPoint(TypedDict):
walk: str
time: datetime
lat: float
lon: float
elevation: float
hr: int
def read_gpx(path: Path) -> list[TrackPoint]:
points: list[TrackPoint] = []
for trkpt in ET.parse(path).getroot().iterfind(".//gpx:trkpt", NS):
points.append(
{
"walk": path.stem,
"time": trkpt.find("gpx:time", NS).text,
"lat": float(trkpt.attrib["lat"]),
"lon": float(trkpt.attrib["lon"]),
"ele": float(trkpt.find("gpx:ele", NS).text),
"hr": int(trkpt.find(".//tpx:hr", NS).text),
}
)
return points
def segments(points: list[TrackPoint]) -> pl.DataFrame:
lat, lon = pl.col("lat").radians(), pl.col("lon").radians()
a = (lat.diff() / 2).sin() ** 2 + lat.cos() * lat.shift().cos() * (lon.diff() / 2).sin() ** 2
return (
pl.LazyFrame(points)
.sort("walk", "time")
.with_columns(
metres=(2 * 6_371_000 * a.sqrt().arcsin()).over("walk"),
climb=pl.col("ele").diff().over("walk"),
seconds=pl.col("time").diff().dt.total_seconds().over("walk"),
)
.drop_nulls(["metres", "climb", "seconds"])
)
def main(paths: list[Path]) -> None:
segs = segments([p for path in paths for p in read_gpx(path)])
summary = duckdb.sql("""
SELECT
walk,
round(sum(metres) / 1000, 1) AS km,
round(sum(greatest(climb, 0))) AS ascent_m,
round(avg(hr)) AS avg_hr,
round(sum(seconds) / 3600, 2) AS hours,
round(sum(metres) / 5000 + sum(greatest(climb, 0)) / 600, 2) AS naismith_hours
FROM segs
GROUP BY walk
ORDER BY walk
""").pl()
print(summary)
if __name__ == "__main__":
main([Path(arg) for arg in sys.argv[1:]])
The comment block at the top is the PEP 723 part. uv run reads it, builds a throwaway environment with those packages and runs the script in it. pyarrow is there because DuckDB reads Polars frames through Arrow, and without it the query fails with No module named 'pyarrow'.
The rest is in three steps. read_gpx turns each <trkpt> element into a TrackPoint. segments works out the distance (the haversine formula, written as Polars expressions), climb and time between each pair of consecutive points, with .over("walk") keeping the two walks apart. Then DuckDB totals it up per walk. DuckDB can query a Polars frame just by naming its Python variable in the SQL, which is why FROM segs works without registering anything.
Running it:
uv run walks.py gpx/*.gpx
The traceback ended with:
_duckdb.InvalidInputException: Invalid Input Error: exporting a stream from the Python object 'segs' failed: InvalidOperationError: sub operation not supported for dtypes `str` and `str`
This error occurred in the following expression:
col("time").diff([dyn int: 1])
while evaluating this larger expression:
col("time").diff([dyn int: 1]).dt.total_seconds()
The timestamps are strings, so Polars can’t subtract them. The traceback points at the .pl() call at the end of main, because segments returned a lazy query and nothing ran until DuckDB asked for the data. The fix is obvious enough, but this is the point where I’d normally fix that one line, run it again, and fix the next thing. This time I asked ty first.
Pointing ty at it
A one-off script deserves a one-off checker, so I ran ty with uvx, which fetches a tool and runs it without installing anything:
uvx ty@1.0.0 check walks.py
error[import-not-found]: Cannot resolve imported module `duckdb`
--> walks.py:11:8
|
11 | import duckdb
| ^^^^^^
info: Searched in the following paths during module resolution:
info: 1. vendored://stdlib (stdlib typeshed stubs vendored by ty)
info: 2. ~/.cache/uv/archive-v0/.../lib/python3.13/site-packages (site-packages)
info: make sure your Python environment is properly configured: https://docs.astral.sh/ty/modules/#python-environment
The same goes for polars. By default ty looks for packages in the current Python environment, and there isn’t one for this script. It still found nine problems in the code that only touches the standard library, but anything involving Polars or DuckDB was unknown, and unknown types pass every check.
The script docs say to turn on the uv integration with the project-manager.script setting. For a single run that’s:
uvx ty@1.0.0 check --config 'project-manager.script="uv"' walks.py
The first time I tried this, ty told me my uv was too old:
error[project-manager]: Setting up the Python environment with uv failed: Found uv 0.9.2, but uv 0.12.3 or newer is required
So you need uv 0.12.3 or newer. I prepended uv 0.13.12 to my PATH for these runs rather than upgrading my own install, though uv self update is the usual fix.
The setting can also go under [tool.ty.project-manager] in a project’s pyproject.toml, or in the script itself, which keeps everything about the script in one file:
# /// script
# requires-python = ">=3.13"
# dependencies = ["polars==2.2.0", "duckdb==2.0.1", "pyarrow"]
#
# [tool.ty.project-manager]
# script = "uv"
# ///
With that in the header, a plain ty check walks.py reports the same 11 errors as below (three lines further down the file). One thing to know from the docs: a [tool.ty] table inside a script replaces the project’s ty settings for that script rather than adding to them.
What it found
With the script’s own environment, ty reported 11 errors. The concise output format puts one on each line:
walks.py:33:13: error[invalid-argument-type] Argument to bound method `list.append` is incorrect: Expected `TrackPoint`, found `dict[str, str | None | float]`
walks.py:33:13: error[missing-typed-dict-key] Missing required key 'elevation' in TypedDict `TrackPoint` constructor
walks.py:35:25: error[invalid-argument-type] Invalid argument to key "time" with declared type `datetime` on TypedDict `TrackPoint`: value of type `str | None`
walks.py:35:25: error[missing-union-attribute] Attribute `text` is not defined on `None` in union `Element[str] | None`
walks.py:38:17: error[unknown-typed-dict-constructor-key] Unknown key "ele" for TypedDict `TrackPoint`
walks.py:38:30: error[invalid-argument-type] Argument to constructor `float.__new__` is incorrect: Expected `str | Buffer | SupportsFloat | SupportsIndex`, found `str | None`
walks.py:38:30: error[missing-union-attribute] Attribute `text` is not defined on `None` in union `Element[str] | None`
walks.py:39:27: error[invalid-argument-type] Argument to constructor `int.__new__` is incorrect: Expected `str | Buffer | SupportsInt | SupportsIndex | SupportsTrunc`, found `str | None`
walks.py:39:27: error[missing-union-attribute] Attribute `text` is not defined on `None` in union `Element[str] | None`
walks.py:49:9: error[invalid-explicit-return] Return type does not match returned value: expected `DataFrame`, found `LazyFrame`
walks.py:62:15: error[missing-union-attribute] Attribute `pl` is not defined on `None` in union `DuckDBPyRelation | None`
Found 11 diagnostics
That’s 11 diagnostics, but five mistakes. The first, on list.append, is the summary: the dict as a whole isn’t a TrackPoint. The rest say why.
The timestamp is still a string
This is the crash I’d already hit. The default output draws it against the code (this is the top of it):
error[invalid-argument-type]: Invalid argument to key "time" with declared type `datetime` on TypedDict `TrackPoint`
--> walks.py:35:25
|
33 | / {
34 | | "walk": path.stem,
35 | | "time": trkpt.find("gpx:time", NS).text,
| | ------ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ value of type `str | None`
| | |
| | key has declared type `datetime`
The difference from the traceback is where it points. Polars noticed two functions and a DuckDB query later. ty points at the line where I put a string in a field I’d said was a datetime. datetime.fromisoformat fixes it, and has handled the Z on the end of Garmin’s timestamps since Python 3.11.
find() can return None
Element.find returns None when there’s no matching child, so .text on the result might fail, and .text can itself be None. That accounts for five of the errors.
This one never crashed. Both files have an elevation, a timestamp and a heart rate on every point (4,725 points on Beinn a’ Chaorainn and 7,675 on Yr Wyddfa). A GPX file recorded without a heart rate monitor would have no hr element, and the script would stop with an AttributeError, because None has no .text. It’s exactly the bug a one-off script keeps until the day it’s run on someone else’s file.
findtext returns the text or None directly, which makes the checks shorter. Points without a time or elevation are skipped, and heart rate becomes optional:
class TrackPoint(TypedDict):
walk: str
time: datetime
lat: float
lon: float
elevation: float
hr: int | None
def read_gpx(path: Path) -> list[TrackPoint]:
points: list[TrackPoint] = []
for trkpt in ET.parse(path).getroot().iterfind(".//gpx:trkpt", NS):
time = trkpt.findtext("gpx:time", namespaces=NS)
ele = trkpt.findtext("gpx:ele", namespaces=NS)
if time is None or ele is None:
continue
hr = trkpt.findtext(".//tpx:hr", namespaces=NS)
points.append(
{
"walk": path.stem,
"time": datetime.fromisoformat(time),
"lat": float(trkpt.attrib["lat"]),
"lon": float(trkpt.attrib["lon"]),
"elevation": float(ele),
"hr": int(hr) if hr is not None else None,
}
)
return points
A missing heart rate ends up as a null in the DataFrame, which DuckDB’s avg ignores.
The key I renamed
I’d named the field elevation in the TypedDict, then typed "ele" when building the dict, because that’s the tag name in the GPX. ty reported both halves: "ele" isn’t a key of TrackPoint, and elevation is missing. The release post shows it suggesting the right key for a near miss. It didn’t offer one here, but the two errors together made it clear enough.
The LazyFrame that should have been a DataFrame
segments says it returns a pl.DataFrame, but I never called .collect(), so it returned a LazyFrame (again, the top of the diagnostic):
error[invalid-explicit-return]: Return type does not match returned value
--> walks.py:49:9
|
45 | def segments(points: list[TrackPoint]) -> pl.DataFrame:
| ------------ Expected `DataFrame` because of return type
At run time this one doesn’t break anything - DuckDB reads a LazyFrame just as happily as a DataFrame - but it’s why the timestamp error surfaced inside DuckDB rather than in segments, and any other caller would have been handed the wrong type. Adding .collect() makes the annotation true.
DuckDB’s sql() might return None
This is the one I’d have argued with. DuckDB 2.0.1 annotates duckdb.sql() as returning DuckDBPyRelation | None. Trying a few statements, the None only came back when the string had no statement in it at all, such as a lone comment. My SELECT will always give a relation, but the type can’t know what’s in the string, so ty is right that .pl() might be called on None. An assert narrows it:
query = duckdb.sql("""
...
""")
assert query is not None
print(query.pl())
The same applies to fetchone(), which returns None when there are no rows. ty flags fetchone()[0] with not-subscriptable, and that one really does crash on an empty table.
With those fixes, ty was happy:
All checks passed!
What it didn’t find
So I ran it, and the traceback ended with:
polars.exceptions.ColumnNotFoundError: unable to find column "ele"; valid columns: ["walk", "time", "lat", "lon", "elevation", "hr"]
I’d fixed the dict key but not pl.col("ele") in segments. ty can’t see this because a Polars column name is just a string, and the type of a DataFrame says nothing about which columns it has. That’s the biggest gap for this kind of script, and it’s worth being clear about what ty couldn’t help with. I checked each of these in a separate file, and ty reported nothing for any of them:
- Column names:
pl.col("meters")on a frame with ametrescolumn. - SQL: a misspelt column inside the string passed to
duckdb.sql(). - DuckDB results:
.pl()is annotated as returningAnyin DuckDB 2.0.1, so nothing done with the result is checked. Calling a method that doesn’t exist on it passed. - Query parameters: DuckDB types
paramsasobject, so passing aPathwhere the SQL expects a string is accepted.
The other thing it can’t do is tell me whether the numbers are right.
The numbers
With pl.col("elevation") fixed, the script finally answered the question it was written for:
shape: (2, 6)
┌─────────────┬──────┬──────────┬────────┬───────┬────────────────┐
│ walk ┆ km ┆ ascent_m ┆ avg_hr ┆ hours ┆ naismith_hours │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ f64 ┆ f64 ┆ f64 ┆ f64 │
╞═════════════╪══════╪══════════╪════════╪═══════╪════════════════╡
│ 21857484938 ┆ 11.5 ┆ 1467.0 ┆ 133.0 ┆ 6.49 ┆ 4.74 │
│ 22173909516 ┆ 14.4 ┆ 2350.0 ┆ 113.0 ┆ 9.21 ┆ 6.8 │
└─────────────┴──────┴──────────┴────────┴───────┴────────────────┘
The distances match the ones in the two walk posts, 11.5 km and 14.4 km. The ascent doesn’t: Garmin’s corrected figures are 950 m and 1,238 m, and the raw track has 1,467 m and 2,350 m. GPS elevation wobbles from point to point, and summing every small rise counts each wobble as climbing. Over 7,675 points that adds up to an extra 1,100 m or so on Yr Wyddfa.
A rolling mean over 25 points (about two minutes of walking, as the watch logged a point every few seconds) smooths most of it out:
smoothed = pl.col("elevation").rolling_mean(25, min_samples=1, center=True)
and climb=smoothed.diff().over("walk") in place of the raw difference:
shape: (2, 6)
┌─────────────┬──────┬──────────┬────────┬───────┬────────────────┐
│ walk ┆ km ┆ ascent_m ┆ avg_hr ┆ hours ┆ naismith_hours │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ f64 ┆ f64 ┆ f64 ┆ f64 │
╞═════════════╪══════╪══════════╪════════╪═══════╪════════════════╡
│ 21857484938 ┆ 11.5 ┆ 922.0 ┆ 133.0 ┆ 6.49 ┆ 3.83 │
│ 22173909516 ┆ 14.4 ┆ 1274.0 ┆ 113.0 ┆ 9.21 ┆ 5.01 │
└─────────────┴──────┴──────────┴────────┴───────┴────────────────┘
Both are now within 3% of Garmin’s figures, which are still the ones I trust. I picked 25 points because it landed close, so this is tuned on exactly two walks.
Beinn a’ Chaorainn took 6.49 hours against Naismith’s 3.83, about 1.7 times as long. That was a winter Grade I/II ridge in snow, which isn’t what Naismith had in mind, and my average heart rate of 133 against 113 on Yr Wyddfa suggests my body agreed. The Yr Wyddfa figure is less useful. hours is the time from the first point to the last, so it includes every stop, and a GPX file doesn’t mark when you stopped. Working out moving time properly from point speeds is a job for another script.
The final version, which ty passes and which printed the table above:
# /// script
# requires-python = ">=3.13"
# dependencies = ["polars==2.2.0", "duckdb==2.0.1", "pyarrow"]
# ///
import sys
import xml.etree.ElementTree as ET
from datetime import datetime
from pathlib import Path
from typing import TypedDict
import duckdb
import polars as pl
NS = {
"gpx": "http://www.topografix.com/GPX/1/1",
"tpx": "http://www.garmin.com/xmlschemas/TrackPointExtension/v1",
}
class TrackPoint(TypedDict):
walk: str
time: datetime
lat: float
lon: float
elevation: float
hr: int | None
def read_gpx(path: Path) -> list[TrackPoint]:
points: list[TrackPoint] = []
for trkpt in ET.parse(path).getroot().iterfind(".//gpx:trkpt", NS):
time = trkpt.findtext("gpx:time", namespaces=NS)
ele = trkpt.findtext("gpx:ele", namespaces=NS)
if time is None or ele is None:
continue
hr = trkpt.findtext(".//tpx:hr", namespaces=NS)
points.append(
{
"walk": path.stem,
"time": datetime.fromisoformat(time),
"lat": float(trkpt.attrib["lat"]),
"lon": float(trkpt.attrib["lon"]),
"elevation": float(ele),
"hr": int(hr) if hr is not None else None,
}
)
return points
def segments(points: list[TrackPoint]) -> pl.DataFrame:
lat, lon = pl.col("lat").radians(), pl.col("lon").radians()
a = (lat.diff() / 2).sin() ** 2 + lat.cos() * lat.shift().cos() * (lon.diff() / 2).sin() ** 2
smoothed = pl.col("elevation").rolling_mean(25, min_samples=1, center=True)
return (
pl.LazyFrame(points)
.sort("walk", "time")
.with_columns(
metres=(2 * 6_371_000 * a.sqrt().arcsin()).over("walk"),
climb=smoothed.diff().over("walk"),
seconds=pl.col("time").diff().dt.total_seconds().over("walk"),
)
.drop_nulls(["metres", "climb", "seconds"])
.collect()
)
def main(paths: list[Path]) -> None:
segs = segments([p for path in paths for p in read_gpx(path)])
query = duckdb.sql("""
SELECT
walk,
round(sum(metres) / 1000, 1) AS km,
round(sum(greatest(climb, 0))) AS ascent_m,
round(avg(hr)) AS avg_hr,
round(sum(seconds) / 3600, 2) AS hours,
round(sum(metres) / 5000 + sum(greatest(climb, 0)) / 600, 2) AS naismith_hours
FROM segs
GROUP BY walk
ORDER BY walk
""")
assert query is not None
print(query.pl())
if __name__ == "__main__":
main([Path(arg) for arg in sys.argv[1:]])
Wrapping up
In an 80-line script, ty found five real mistakes: one had already crashed, one would have crashed on the first GPX file without heart rate, and the rest were annotations that didn’t match what the code did. It missed the next crash, because Polars column names and SQL are strings a type checker can’t see into. I’d never type checked a script like this because setting up an environment for the checker was more work than the script. Now it’s one line in the header.