| 1 |
========= |
| 2 |
Packaging |
| 3 |
========= |
| 4 |
Packaging is bundling up your python library so that it can be easily ``pip install`` by others. |
| 5 |
|
| 6 |
Typically this involves: |
| 7 |
|
| 8 |
1. Bundling the code into a Built Distribution (wheel) and/or Source Distribution (sdist). |
| 9 |
|
| 10 |
2. Uploading (publishing) the distribution(s) to python package repository, like PyPI. |
| 11 |
|
| 12 |
This section is a brief bootcamp on package **configuration** for a CLI application. |
| 13 |
This is **not** intended to be a complete tutorial on python packaging and publishing. |
| 14 |
In this tutorial, replace all instances of ``mypackage`` with your own project name. |
| 15 |
|
| 16 |
--------------- |
| 17 |
\_\_main\_\_.py |
| 18 |
--------------- |
| 19 |
|
| 20 |
In python, if you have a module ``mypackage/__main__.py``, it will be executed with the bash command ``python -m mypackage``. |
| 21 |
|
| 22 |
A pretty bare-bones Cyclopts ``mypackage/__main__.py`` will look like: |
| 23 |
|
| 24 |
.. code-block:: python |
| 25 |
|
| 26 |
# mypackage/__main__.py |
| 27 |
|
| 28 |
import cyclopts |
| 29 |
|
| 30 |
app = cyclopts.App() |
| 31 |
|
| 32 |
@app.command |
| 33 |
def foo(name: str): |
| 34 |
print(f"Hello {name}!") |
| 35 |
|
| 36 |
if __name__ == "__main__": |
| 37 |
app() |
| 38 |
|
| 39 |
|
| 40 |
.. code-block:: console |
| 41 |
|
| 42 |
$ python -m mypackage World |
| 43 |
Hello World! |
| 44 |
|
| 45 |
----------- |
| 46 |
Entrypoints |
| 47 |
----------- |
| 48 |
If you want your application to be callable like a standard bash executable (i.e. ``my-package`` instead of ``python -m mypackage``), we'll need to add an entrypoint_. |
| 49 |
|
| 50 |
Modern Python projects typically use ``pyproject.toml`` for configuration. The standard way to define console scripts is: |
| 51 |
|
| 52 |
.. code-block:: toml |
| 53 |
|
| 54 |
# pyproject.toml |
| 55 |
[project.scripts] |
| 56 |
my-package = "mypackage.__main__:app" |
| 57 |
|
| 58 |
This creates an executable named ``my-package`` that executes the callable ``app`` object (from the right of the colon) from the python module ``mypackage.__main__``. |
| 59 |
Note that this configuration is independent of any special naming, like ``__main__`` or ``app``. |
| 60 |
|
| 61 |
^^^^^^^^^^^^^^^^^^^^^ |
| 62 |
Legacy Configurations |
| 63 |
^^^^^^^^^^^^^^^^^^^^^ |
| 64 |
|
| 65 |
For older projects, you may encounter these alternative formats: |
| 66 |
|
| 67 |
**setup.py:** |
| 68 |
|
| 69 |
.. code-block:: python |
| 70 |
|
| 71 |
# setup.py |
| 72 |
from setuptools import setup |
| 73 |
|
| 74 |
setup( |
| 75 |
# There should be a lot more fields populated here. |
| 76 |
entry_points={ |
| 77 |
"console_scripts": [ |
| 78 |
"my-package = mypackage.__main__:app", |
| 79 |
] |
| 80 |
}, |
| 81 |
) |
| 82 |
|
| 83 |
**setup.cfg:** |
| 84 |
|
| 85 |
.. code-block:: cfg |
| 86 |
|
| 87 |
# setup.cfg |
| 88 |
[options.entry_points] |
| 89 |
console_scripts = |
| 90 |
my-package = mypackage.__main__:app |
| 91 |
|
| 92 |
**Poetry:** |
| 93 |
|
| 94 |
.. code-block:: toml |
| 95 |
|
| 96 |
# pyproject.toml |
| 97 |
[tool.poetry.scripts] |
| 98 |
my-package = "mypackage.__main__:app" |
| 99 |
|
| 100 |
The setuptools entrypoint_ documentation goes into further detail. |
| 101 |
|
| 102 |
.. _Result Action: |
| 103 |
|
| 104 |
------------- |
| 105 |
Result Action |
| 106 |
------------- |
| 107 |
|
| 108 |
When using Cyclopts as a CLI application, command return values are automatically handled appropriately. By default, :class:`~cyclopts.App` uses ``"print_non_int_sys_exit"`` mode, which calls :func:`sys.exit` with the appropriate exit code: |
| 109 |
|
| 110 |
- String returns are printed to stdout, then :func:`sys.exit(0) <sys.exit>` is called |
| 111 |
- Integer returns are passed to :func:`sys.exit(int) <sys.exit>` as the exit code |
| 112 |
- Boolean returns are converted: :obj:`True` → :func:`sys.exit(0) <sys.exit>`, :obj:`False` → :func:`sys.exit(1) <sys.exit>` |
| 113 |
- :obj:`None` returns call :func:`sys.exit(0) <sys.exit>` |
| 114 |
|
| 115 |
This default behavior makes Cyclopts applications work consistently whether run directly as scripts or installed via `console_scripts entry points <https://packaging.python.org/en/latest/specifications/entry-points/#use-for-scripts>`_. The :attr:`~cyclopts.App.result_action` can be customized if different behavior is needed: |
| 116 |
|
| 117 |
|
| 118 |
.. _custom-return-code-protocol: |
| 119 |
|
| 120 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 121 |
Custom Return Code Protocol |
| 122 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 123 |
|
| 124 |
Whenever a built-in :attr:`~cyclopts.App.result_action` would otherwise use ``0`` as the exit code, Cyclopts checks the return value for a ``__cyclopts_returncode__`` method. If present, its return value is used as the exit code instead. This lets returned objects describe their own success/failure without forcing the CLI layer to translate them. |
| 125 |
|
| 126 |
A common use case is a CLI that wraps a library and returns rich result objects directly, deferring presentation to the object's ``__rich__`` method: |
| 127 |
|
| 128 |
.. code-block:: python |
| 129 |
|
| 130 |
from cyclopts import App |
| 131 |
|
| 132 |
|
| 133 |
class HealthCheck: |
| 134 |
def __init__(self, service: str, healthy: bool): |
| 135 |
self.service = service |
| 136 |
self.healthy = healthy |
| 137 |
|
| 138 |
def __rich__(self) -> str: |
| 139 |
status = "[green]OK[/green]" if self.healthy else "[red]FAIL[/red]" |
| 140 |
return f"{self.service}: {status}" |
| 141 |
|
| 142 |
def __cyclopts_returncode__(self) -> int: |
| 143 |
return 0 if self.healthy else 1 |
| 144 |
|
| 145 |
|
| 146 |
app = App() |
| 147 |
|
| 148 |
|
| 149 |
@app.command |
| 150 |
def check(service: str) -> HealthCheck: |
| 151 |
"""Check the health of a service.""" |
| 152 |
return HealthCheck(service, healthy=ping(service)) |
| 153 |
|
| 154 |
|
| 155 |
app() |
| 156 |
|
| 157 |
.. code-block:: console |
| 158 |
|
| 159 |
$ my-script check database; echo "exit=$?" |
| 160 |
database: OK |
| 161 |
exit=0 |
| 162 |
|
| 163 |
$ my-script check cache; echo "exit=$?" |
| 164 |
cache: FAIL |
| 165 |
exit=1 |
| 166 |
|
| 167 |
The protocol is opt-in: objects that don't define ``__cyclopts_returncode__`` continue to use the previous ``0`` default. The method must be a zero-argument callable that returns an :class:`int`; non-callable attributes are ignored. Branches that derive their exit code from an :class:`int` or :class:`bool` return value (e.g. ``sys.exit(result)``) ignore the protocol — return an integer/bool directly to set those exit codes. |
| 168 |
|
| 169 |
Custom ``result_action`` callables can opt into the same protocol via :func:`cyclopts.resolve_returncode`: |
| 170 |
|
| 171 |
.. code-block:: python |
| 172 |
|
| 173 |
import sys |
| 174 |
from typing import Any |
| 175 |
|
| 176 |
from cyclopts import App, resolve_returncode |
| 177 |
|
| 178 |
|
| 179 |
def result_action(result: Any) -> None: |
| 180 |
if isinstance(result, bool): |
| 181 |
sys.exit(0 if result else 1) |
| 182 |
if isinstance(result, int): |
| 183 |
sys.exit(result) |
| 184 |
if result is not None: |
| 185 |
print(result) |
| 186 |
sys.exit(resolve_returncode(result)) |
| 187 |
|
| 188 |
|
| 189 |
app = App(result_action=result_action) |
| 190 |
|
| 191 |
|
| 192 |
.. _Poetry: https://python-poetry.org |
| 193 |
.. _entrypoint: https://setuptools.pypa.io/en/latest/userguide/entry_point.html#entry-points |