PEP 723: Embedding pyproject.toml in single-file scripts

As an alternative to “syntactic” __pyproject__ (which I do not like at all), what about a generic format for embeddable metadata comments?

I suggested something similar in the PEP 722 thread: PEP 722: Dependency specification for single-file scripts - #321 by gwerbin

For example, here’s how one might embed pyproject.toml in a Python script:

#!/usr/bin/env python3

# -*- pyproject:
# [project]
# dependencies = [
#   'sqlalchemy',
#   'click',
# ]
# -*-

if __name__ == "__main__":
    print("hello!")

Perhaps these -*- blocks, which are already in informal use, could be systematized, and thereby adapted for both PEP 722 and 723.

Yet another option (not incompatible with the above) would be to add syntactic support in Python itself for either “front matter” or “back matter” that is not necessarily embedded in a comment. Back matter might be easier to implement, because you can hide it behind some kind of special token like __END__ or __DATA__ like in Perl (see here).

#!/usr/bin/env python3

# Standard "coding" declaration
# -*- coding: utf-8 -*-

# PEP 722 dependencies
# -*- script dependencies:
#   click
#   httpx
# -*-

if __name__ == "__main__":
    print("hello!")

__DATA__

-*- pyproject:
[project]
name = 'all-in-one-demo'
license = { text = "MIT" }
-*-

Edit: A sort of informal “spec” here is that the pattern -*- delimits a metadata region, which can be one line or multiple lines, and the first : therein delimits the name/key of the region from the content/value. So the above script would have metadata that looks something like this (as a Python literal):

{
    "coding": "utf-8",
    "script dependencies": r"""
   click
   httpx
""",
    "pyproject": r"""
[project]
name = 'all-in-one-demo'
license = { text = "MIT" }
"""
}

Beyond that, the content would be the responsibility of the relevant tools to parse. This is a lot like how IPython magics work.

6 Likes