| 1 |
.. _Args & Kwargs: |
| 2 |
|
| 3 |
============= |
| 4 |
Args & Kwargs |
| 5 |
============= |
| 6 |
|
| 7 |
In python, a function can consume a variable number of positional and keyword arguments: |
| 8 |
|
| 9 |
.. code-block:: python |
| 10 |
|
| 11 |
def foo(normal_required_variable, *args, **kwargs): |
| 12 |
pass |
| 13 |
|
| 14 |
There is **nothing special** about the names ``args`` and ``kwargs``; |
| 15 |
the functionality is derived from the leading ``*`` and ``**``. |
| 16 |
``args`` and ``kwargs`` are the defacto standard names for these variables. |
| 17 |
In this document, we'll usually just refer to them as ``*args`` and ``**kwargs``. |
| 18 |
|
| 19 |
Cyclopts commands may consume a variable number of positional and keyword arguments. |
| 20 |
The priority ruleset is as follows: |
| 21 |
|
| 22 |
1. ``--keyword`` CLI arguments first get matched to normal variable parameters. |
| 23 |
|
| 24 |
2. Unmatched keywords get consumed by ``**kwargs``, if specified. |
| 25 |
|
| 26 |
3. All remaining tokens get consumed by ``*args``, if specified. |
| 27 |
A prevalant use-case is in a typical :ref:`Meta App`. |
| 28 |
|
| 29 |
.. _Args & Kwargs - Args: |
| 30 |
|
| 31 |
-------------------------- |
| 32 |
Args (Variable Positional) |
| 33 |
-------------------------- |
| 34 |
A variable number of positional arguments consume all remaining positional arguments from the command-line. |
| 35 |
Individual elements are converted to the annotated type. |
| 36 |
|
| 37 |
.. code-block:: python |
| 38 |
|
| 39 |
from cyclopts import App |
| 40 |
|
| 41 |
app = App() |
| 42 |
|
| 43 |
@app.command |
| 44 |
def foo(name: str, *favorite_numbers: int): |
| 45 |
print(f"{name}'s favorite numbers are: {favorite_numbers}") |
| 46 |
|
| 47 |
app() |
| 48 |
|
| 49 |
|
| 50 |
.. code-block:: console |
| 51 |
|
| 52 |
$ my-script foo Brian |
| 53 |
Brian's favorite numbers are: () |
| 54 |
|
| 55 |
$ my-script foo Brian 777 |
| 56 |
Brian's favorite numbers are: (777,) |
| 57 |
|
| 58 |
$ my-script foo Brian 777 2 |
| 59 |
Brian's favorite numbers are: (777, 2) |
| 60 |
|
| 61 |
.. _Args & Kwargs - Kwargs: |
| 62 |
|
| 63 |
-------------------------- |
| 64 |
Kwargs (Variable Keywords) |
| 65 |
-------------------------- |
| 66 |
A variable number of keyword arguments consume all remaining CLI tokens starting with ``--``. |
| 67 |
Individual values are converted to the annotated type. |
| 68 |
|
| 69 |
.. code-block:: python |
| 70 |
|
| 71 |
from cyclopts import App |
| 72 |
|
| 73 |
app = App() |
| 74 |
|
| 75 |
@app.command |
| 76 |
def add(**country_to_capitols): |
| 77 |
for country, capitol in country_to_capitols.items(): |
| 78 |
print(f"Adding {country} with capitol {capitol}.") |
| 79 |
|
| 80 |
app() |
| 81 |
|
| 82 |
|
| 83 |
.. code-block:: console |
| 84 |
|
| 85 |
$ my-script add --united-states="Washington, D.C." --canada=Ottawa |
| 86 |
Adding united-states with capitol Washington, D.C.. |
| 87 |
Adding canada with capitol Ottawa. |