Defining Python dependencies at the top of the file
Earlier in the year, I wrote about updating Flickr metadata using Python. For this script to work, I needed to install the flickrapi package first.
I recently came across PEP 723 – Inline script metadata that makes this much easier for single file scripts like my sync-flickr-dates script.
Essentially, we can now put a special comment block at the top of the file, before our import statements like this:
# /// script
# requires-python = ">=3.11"
# dependencies = [
# "flickrapi",
# ]
# ///
The Python version is optional and we could specify a specific version constraint on each package should we wish to.
Now, when we run with uv, uv will ensure that the flickrapi package is installed for us.
$ uv run sync-flickr-dates.py Reading inline script metadata from: sync-flickr-dates.py Installed 10 packages in 13ms usage: sync-flickr-dates.py [-h] photo_ids
In this case, uv will create a Python 3.12 venv for us. For me this is in ~/.cache/uv (which you can find via uv cache dir).
Such a nice way to run a Python script and saves faffing with a venv manually, so I expect to be learning more about uv over time as it looks promising.
It’s also motivating me to consider using Python for more one-off scripts where I would usually use bash.
This is an excellent tip, thank you. I'll port all my Python scripts over straight away :)
It's probably worth saying that Python can cover almost all of the capability of bash without needed any dependencies outside of the standard Python library though, so even without this, Python would be a good substitute for bash in many cases.