| 1 |
================== |
| 2 |
Sharing Parameters |
| 3 |
================== |
| 4 |
Many subcommands within a CLI may take the same parameters. |
| 5 |
For example, all commands for a CLI that deals with a remote server might need a ``url`` and ``port`` number. |
| 6 |
Furthermore, there might be common setup required, such as connecting to the remote server. |
| 7 |
If you are familiar with `Click`_, this would be accomplished with `contexts <https://click.palletsprojects.com/en/stable/complex/>`_. |
| 8 |
In Cyclopts, there are 2 ways to accomplish this: |
| 9 |
|
| 10 |
1. With a :ref:`meta app <Meta App>`. While powerful, it's admittantly a bit heavy-handed and clunky. |
| 11 |
|
| 12 |
2. Via a common dataclass that is passed to each command. While less powerful than using a meta-app, |
| 13 |
it still accomplishes many of the same goals with simpler, terser code. |
| 14 |
|
| 15 |
In this section, we'll be investigating option (2) by constructing an example application that has 2 commands: |
| 16 |
|
| 17 |
1. ``create`` - Connect to a server and send a POST command to it. |
| 18 |
|
| 19 |
2. ``info`` - Connect to a server and GET information about a user. |
| 20 |
|
| 21 |
|
| 22 |
.. code-block:: python |
| 23 |
|
| 24 |
# demo.py |
| 25 |
from cyclopts import App, Parameter |
| 26 |
from cyclopts.types import UInt16 |
| 27 |
from dataclasses import dataclass |
| 28 |
from functools import cached_property |
| 29 |
from httpx import Client |
| 30 |
|
| 31 |
@Parameter(name="*") # Flatten the namespace; i.e. option will be "--url" instead of "--common.url" |
| 32 |
@dataclass |
| 33 |
class Common: |
| 34 |
url: str = "http://cyclopts.readthedocs.io" |
| 35 |
"URL of remote server." |
| 36 |
|
| 37 |
port: UInt16 = 8080 # an "int" that is limited to range [0, 65535] |
| 38 |
"Port of remote server." |
| 39 |
|
| 40 |
verbose: bool = False |
| 41 |
"Increased printing verbosity." |
| 42 |
|
| 43 |
def __post_init__(self): |
| 44 |
# dataclasses call this method after calling the auto-generated __init__. |
| 45 |
if self.verbose: |
| 46 |
print(f"Server: {self.base_url}") |
| 47 |
|
| 48 |
@property |
| 49 |
def base_url(self) -> str: |
| 50 |
return f"{self.url}:{self.port}" |
| 51 |
|
| 52 |
@cached_property |
| 53 |
def client(self) -> Client: |
| 54 |
return Client(base_url=self.base_url) |
| 55 |
|
| 56 |
app = App() |
| 57 |
|
| 58 |
@app.command |
| 59 |
def create(name: str, age: int, *, common: Common | None = None): |
| 60 |
"""Create a user on remote server. |
| 61 |
|
| 62 |
Parameters |
| 63 |
---------- |
| 64 |
name: str |
| 65 |
Name of the user to create. |
| 66 |
age: int |
| 67 |
Age of the user in years. |
| 68 |
""" |
| 69 |
if common is None: |
| 70 |
common = Common() |
| 71 |
json = {"name": name, "age": age} |
| 72 |
if common.verbose: |
| 73 |
print(f"Creating user: {json}") |
| 74 |
common.client.post("/users", json=json) |
| 75 |
# TODO: in a real application, we should error-check the response here. |
| 76 |
|
| 77 |
@app.command |
| 78 |
def info(name: str, *, common: Common | None = None): |
| 79 |
"""List a user on remote server. |
| 80 |
|
| 81 |
Parameters |
| 82 |
---------- |
| 83 |
name: str |
| 84 |
Name of the user to get info about. |
| 85 |
""" |
| 86 |
if common is None: |
| 87 |
common = Common() |
| 88 |
response = common.client.get("/users", params={"name": name}) |
| 89 |
user = response.json() |
| 90 |
print(f"User: {user}") |
| 91 |
|
| 92 |
if __name__ == "__main__": |
| 93 |
app() |
| 94 |
|
| 95 |
From the root help-page, we can see our two commands: |
| 96 |
|
| 97 |
.. code-block:: console |
| 98 |
|
| 99 |
$ python demo.py --help |
| 100 |
Usage: demo.py COMMAND |
| 101 |
|
| 102 |
╭─ Commands ─────────────────────────────────────────────────────────────────╮ |
| 103 |
│ create Create a user on remote server. │ |
| 104 |
│ info List a user on remote server. │ |
| 105 |
│ --help -h Display this message and exit. │ |
| 106 |
│ --version Display application version. │ |
| 107 |
╰────────────────────────────────────────────────────────────────────────────╯ |
| 108 |
|
| 109 |
From the ``create`` help-page, we can see all of our parameters: |
| 110 |
|
| 111 |
.. code-block:: console |
| 112 |
|
| 113 |
$ python demo.py create --help |
| 114 |
Usage: demo.py create [ARGS] [OPTIONS] |
| 115 |
|
| 116 |
Create a user on remote server. |
| 117 |
|
| 118 |
╭─ Parameters ───────────────────────────────────────────────────────────────╮ |
| 119 |
│ * NAME --name Name of the user to create. [required] │ |
| 120 |
│ * AGE --age Age of the user in years. [required] │ |
| 121 |
│ --url URL of remote server. [default: │ |
| 122 |
│ http://cyclopts.readthedocs.io] │ |
| 123 |
│ --port Port of remote server. [default: 8080] │ |
| 124 |
│ --verbose --no-verbose Increased printing verbosity. [default: False] │ |
| 125 |
╰────────────────────────────────────────────────────────────────────────────╯ |
| 126 |
|
| 127 |
Some example command-line invocations: |
| 128 |
|
| 129 |
.. code-block:: console |
| 130 |
|
| 131 |
$ python demo.py create Alice 42 |
| 132 |
# No response from the CLI. |
| 133 |
|
| 134 |
$ python demo.py create Alice 42 --verbose |
| 135 |
Creating user: {'name': 'Alice', 'age': 42} |
| 136 |
|
| 137 |
By organizing the code this way, we can centralize shared parameters and logic between many commands. |
| 138 |
|
| 139 |
.. _Click: https://click.palletsprojects.com |