TIL: One file to rule them all: PEP-723 and uv

About 1 min reading time

It's impressive what’s possible with Python nowadays! PEP-723 introduces a way to define metadata directly inside a Python file — including dependencies.

"This PEP specifies a metadata format that can be embedded in single-file Python scripts to assist launchers, IDEs and other external tools which may need to interact with such scripts."
PEP 723 – Inline script metadata

uv takes this a step further by handling virtual environments and dependencies seamlessly when executing such scripts.

For example, if you want to spin up a Flask server in one file, it looks like this:

# /// script
# requires-python = ">=3.12"
# dependencies = [
#   "flask",
# ]
# ///
from flask import Flask

app = Flask(__name__)

@app.route("/")
def home():
    return "Hello, World! 🚀"

if __name__ == "__main__":
    app.run(debug=True)

Save this file as server.py and run it with:

uv run server.py

Within seconds, the server is up and running. This makes it easy to execute Python scripts with external dependencies — without worrying about setting up a virtual environment manually.

Even better, you can make it a standalone executable script by adding this shebang at the top:

#!/usr/bin/env -S uv run --script

Now, the script will be executed using uv whenever it’s run (just ensure it's executable with chmod +x).

This approach offers a useful way to define and run Python scripts while handling dependencies — all within a single file.

Thanks to Rob Allen for writing about PEP-723 and how to use uv as a shebang line.


This post is based on my opinion and experience. It is based on what worked for me in my context. I recognize, that your context is different.
The "Just Sharing" Principle