1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
| #!/usr/bin/env scriptisto
from typing import Annotated
import msgspec
from msgspec import Meta, Struct
PlayerName = Annotated[str, Meta(min_length=1, pattern="^[A-Z][a-z]*$")]
class Player(Struct, forbid_unknown_fields=True):
name: PlayerName
score: Annotated[int, Meta(ge=0, le=10)]
class Game(Struct, forbid_unknown_fields=True):
players: Annotated[list[Player], Meta(min_length=1)]
winner: PlayerName
game = msgspec.json.decode(
b'{"players":[{"name":"Alan","score":2},{"name":"Bob","score":7}],"winner":"Bob"}',
type=Game,
)
print(game)
print(game.players[0].name)
try:
msgspec.json.decode(b'{"players":[{"name":"Bob","score":7}]}', type=Game)
except Exception as exc:
print(f"Error when the winner is missing: {exc}")
try:
msgspec.json.decode(b'{"players":[],"winner":"Bob"}', type=Game)
except Exception as exc:
print(f"Error when the player list is empty: {exc}")
try:
msgspec.json.decode(
b'{"players":[{"name":"Bob","score":"7"}],"winner":"Bob"}',
type=Game,
)
except Exception as exc:
print(f"Error when the score is not an integer: {exc}")
"""
scriptisto-begin
script_src: me.py
build_once_cmd: python build_venv.py && chmod +x script
build_cmd: ./venv/bin/mypy me.py && ./venv/bin/ruff check me.py
files:
- path: requirements.txt
content: |
msgspec==0.17.0
mypy==1.4.1
ruff==0.0.284
- path: build_venv.py
content: |
from pathlib import Path
from subprocess import check_call, check_output
python_version = "3.11.4"
pyenv_root = Path(check_output(("pyenv", "root")).decode("utf-8").strip())
pyenv_python_dir = pyenv_root / f"versions/{python_version}"
if not pyenv_python_dir.is_dir():
check_call(("pyenv", "install", python_version))
check_call((pyenv_python_dir / "bin/python", "-m", "venv", "venv"))
check_call(("venv/bin/python", "-m", "pip", "install", "--upgrade", "pip"))
check_call(("venv/bin/python", "-m", "pip", "install", "-r", "requirements.txt"))
- path: script
content: |
#!/bin/sh
DIR="$(cd "$(dirname "$0")" && pwd)"
exec "$DIR/venv/bin/python" "$DIR/me.py" "$@"
scriptisto-end
""" |
Partager