Skip to content
Myr

:memo: :sparkles: :heavy_check_mark: CLI parameters: docs, refactor/upgrade, tests.

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Sebastián Ramírez · committed by GitHub · parents 355c223, cebdfbb · Browse files · 56 files+1577 added−13 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

56 files+1577 added−13 removed

  • tests:+616 added−0 removed
  • other:+961 added−13 removed

56 files+1577 added−13 removed

added:docs/src/parameter_types/datetime/__init__.py
added:docs/src/parameter_types/datetime/tutorial001.py+12 added
1from datetime import datetime23import typer456def main(birth: datetime):7 typer.echo(f"Interesting day to be born: {birth}")8 typer.echo(f"Birth hour: {birth.hour}")91011if __name__ == "__main__":12 typer.run(main)
added:docs/src/parameter_types/datetime/tutorial002.py+15 added
1from datetime import datetime23import typer456def main(7 launch_date: datetime = typer.Argument(8 ..., formats=["%Y-%m-%d", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%d %H:%M:%S", "%m/%d/%Y"]9 )10):11 typer.echo(f"Launch will be at: {launch_date}")121314if __name__ == "__main__":15 typer.run(main)
added:docs/src/parameter_types/enum/__init__.py
added:docs/src/parameter_types/enum/tutorial001.py+17 added
1from enum import Enum23import typer456class NeuralNetwork(str, Enum):7 simple = "simple"8 conv = "conv"9 lstm = "lstm"101112def main(network: NeuralNetwork = NeuralNetwork.simple):13 typer.echo(f"Training neural network of type: {network.value}")141516if __name__ == "__main__":17 typer.run(main)
added:docs/src/parameter_types/enum/tutorial002.py+19 added
1from enum import Enum23import typer456class NeuralNetwork(str, Enum):7 simple = "simple"8 conv = "conv"9 lstm = "lstm"101112def main(13 network: NeuralNetwork = typer.Option(NeuralNetwork.simple, case_sensitive=False)14):15 typer.echo(f"Training neural network of type: {network.value}")161718if __name__ == "__main__":19 typer.run(main)
added:docs/src/parameter_types/file/__init__.py
added:docs/src/parameter_types/file/tutorial001.py+10 added
1import typer234def main(config: typer.FileText = typer.Option(...)):5 for line in config:6 typer.echo(f"Config line: {line}")789if __name__ == "__main__":10 typer.run(main)
added:docs/src/parameter_types/file/tutorial002.py+10 added
1import typer234def main(config: typer.FileTextWrite = typer.Option(...)):5 config.write("Some config written by the app")6 typer.echo("Config written")789if __name__ == "__main__":10 typer.run(main)
added:docs/src/parameter_types/file/tutorial003.py+13 added
1import typer234def main(file: typer.FileBinaryRead = typer.Option(...)):5 processed_total = 06 for bytes_chunk in file:7 # Process the bytes in bytes_chunk8 processed_total += len(bytes_chunk)9 typer.echo(f"Processed bytes total: {processed_total}")101112if __name__ == "__main__":13 typer.run(main)
added:docs/src/parameter_types/file/tutorial004.py+17 added
1import typer234def main(file: typer.FileBinaryWrite = typer.Option(...)):5 first_line_str = "some settings\n"6 # You cannot write str directly to a binary file, you have to encode it to get bytes7 first_line_bytes = first_line_str.encode("utf-8")8 # Then you can write the bytes9 file.write(first_line_bytes)10 # This is already bytes, it starts with b"11 second_line = b"la cig\xc3\xbce\xc3\xb1a trae al ni\xc3\xb1o"12 file.write(second_line)13 typer.echo("Binary file written")141516if __name__ == "__main__":17 typer.run(main)
added:docs/src/parameter_types/file/tutorial005.py+10 added
1import typer234def main(config: typer.FileText = typer.Option(..., mode="a")):5 config.write("This is a single line\n")6 typer.echo("Config line written")789if __name__ == "__main__":10 typer.run(main)
added:docs/src/parameter_types/index/__init__.py
added:docs/src/parameter_types/index/tutorial001.py+14 added
1import typer234def main(5 name: str, age: int = 20, height_meters: float = 1.89, female: bool = True,6):7 typer.echo(f"NAME is {name}, of type: {type(name)}")8 typer.echo(f"--age is {age}, of type: {type(age)}")9 typer.echo(f"--height-meters is {height_meters}, of type: {type(height_meters)}")10 typer.echo(f"--female is {female}, of type: {type(female)}")111213if __name__ == "__main__":14 typer.run(main)
added:docs/src/parameter_types/number/__init__.py
added:docs/src/parameter_types/number/tutorial001.py+15 added
1import typer234def main(5 id: int = typer.Argument(..., min=0, max=1000),6 age: int = typer.Option(20, min=18),7 score: float = typer.Option(0, max=100),8):9 typer.echo(f"ID is {id}")10 typer.echo(f"--age is {age}")11 typer.echo(f"--score is {score}")121314if __name__ == "__main__":15 typer.run(main)
added:docs/src/parameter_types/number/tutorial002.py+15 added
1import typer234def main(5 id: int = typer.Argument(..., min=0, max=1000),6 rank: int = typer.Option(0, max=10, clamp=True),7 score: float = typer.Option(0, min=0, max=100, clamp=True),8):9 typer.echo(f"ID is {id}")10 typer.echo(f"--rank is {rank}")11 typer.echo(f"--score is {score}")121314if __name__ == "__main__":15 typer.run(main)
added:docs/src/parameter_types/path/__init__.py
added:docs/src/parameter_types/path/tutorial001.py+17 added
1from pathlib import Path23import typer456def main(config: Path = typer.Option(...)):7 if config.is_file():8 text = config.read_text()9 typer.echo(f"Config file contents: {text}")10 elif config.is_dir():11 typer.echo("Config is a directory, will use all its config files")12 elif not config.exists():13 typer.echo("The config doesn't exist")141516if __name__ == "__main__":17 typer.run(main)
added:docs/src/parameter_types/path/tutorial002.py+22 added
1from pathlib import Path23import typer456def main(7 config: Path = typer.Option(8 ...,9 exists=True,10 file_okay=True,11 dir_okay=False,12 writable=False,13 readable=True,14 resolve_path=True,15 )16):17 text = config.read_text()18 typer.echo(f"Config file contents: {text}")192021if __name__ == "__main__":22 typer.run(main)
added:docs/src/parameter_types/uuid/__init__.py
added:docs/src/parameter_types/uuid/tutorial001.py+12 added
1from uuid import UUID23import typer456def main(user_id: UUID):7 typer.echo(f"USER_ID is {user_id}")8 typer.echo(f"UUID version is: {user_id.version}")91011if __name__ == "__main__":12 typer.run(main)
added:docs/tutorial/parameter-types/datetime.md+79 added
1You can specify a *CLI parameter* as a Python <a href="https://docs.python.org/3/library/datetime.html" target="_blank">`datetime`</a>.23Your function will receive a standard Python `datetime` object, and again, your editor will give you completion, etc.45```Python hl_lines="1 6 7 8"6{!./src/parameter_types/datetime/tutorial001.py!}7```89By default, it will expect a datetime in ISO format in the input.1011Check it:1213<div class="termy">1415```console16$ python main.py --help1718Usage: main.py [OPTIONS] [%Y-%m-%d|%Y-%m-%dT%H:%M:%S|%Y-%m-%d %H:%M:%S]1920Options:21 --install-completion Install completion for the current shell.22 --show-completion Show completion for the current shell, to copy it or customize the installation.23 --help Show this message and exit.2425// Pass a datetime26$ python main.py 1956-01-31T10:00:002728Interesting day to be born: 1956-01-31 10:00:0029Birth hour: 103031// An invalid date32$ python main.py july-19-19893334Usage: main.py [OPTIONS] [%Y-%m-%d|%Y-%m-%dT%H:%M:%S|%Y-%m-%d%H:%M:%S]3536Error: Invalid value for "[%Y-%m-%d|%Y-%m-%dT%H:%M:%S|%Y-%m-%d %H:%M:%S]": invalid datetime format: july-19-1989. (choose from %Y-%m-%d, %Y-%m-%dT%H:%M:%S, %Y-%m-%d %H:%M:%S)37```3839</div>4041## Custom date format4243You can also customize the formats received for the `datetime` with the `formats` parameter.4445`formats` receives a list of strings with the date formats that would be passed to <a href="https://docs.python.org/3/library/datetime.html#datetime.date.strftime" target="_blank">datetime.strptime()</a>.4647For example, let's imagine that you want to accept an ISO formatted datetime, but for some strange reason, you also want to accept a format with:4849* first the month50* then the day51* then the year52* separated with "`/`"5354...It's a crazy example, but let's say you also needed that strange format:5556```Python hl_lines="8"57{!./src/parameter_types/datetime/tutorial002.py!}58```5960!!! tip61 Notice the last string in `formats`: `"%m/%d/%Y"`.6263Check it:6465<div class="termy">6667```console68// ISO dates work69$ python main.py 1969-10-297071Launch will be at: 1969-10-29 00:00:007273// But the strange custom format also works74$ python main.py 10/29/19697576Launch will be at: 1969-10-29 00:00:0077```7879</div>
added:docs/tutorial/parameter-types/enum.md+68 added
1To define a *CLI parameter* that can take a value from a predefined set of values you can use a standard Python <a href="https://docs.python.org/3/library/enum.html" target="_blank">`enum.Enum`</a>:23```Python hl_lines="1 6 7 8 9 12 13"4{!./src/parameter_types/enum/tutorial001.py!}5```67!!! tip8 Notice that the function parameter `network` will be an `Enum`, not a `str`.910 To get the `str` value in your function's code use `network.value`.1112Check it:1314<div class="termy">1516```console17$ python main.py --help1819// Notice the predefined values [simple|conv|lstm]20Usage: main.py [OPTIONS]2122Options:23 --network [simple|conv|lstm]24 --install-completion Install completion for the current shell.25 --show-completion Show completion for the current shell, to copy it or customize the installation.26 --help Show this message and exit.2728// Try it29$ python main.py --network conv3031Training neural network of type: conv3233// Invalid value34$ python main.py --network capsule3536Usage: main.py [OPTIONS]37Try "main.py --help" for help.3839Error: Invalid value for "--network": invalid choice: capsule. (choose from simple, conv, lstm)40```4142</div>4344### Case insensitive Enum choices4546You can make an `Enum` (choice) *CLI parameter* be case-insensitive with the `case_sensitive` parameter:4748```Python hl_lines="13"49{!./src/parameter_types/enum/tutorial002.py!}50```5152And then the values of the `Enum` will be checked no matter if lower case, upper case, or a mix:5354<div class="termy">5556```console57// Notice the upper case CONV58$ python main.py --network CONV5960Training neural network of type: conv6162// A mix also works63$ python main.py --network LsTm6465Training neural network of type: lstm66```6768</div>
added:docs/tutorial/parameter-types/file.md+248 added
1Apart from `Path` *CLI parameters* you can also declare some types of "files".23!!! tip4 In most of the cases you are probably fine just using `Path`.56 You can read and write data with `Path` the same way.78The difference is that these types will give you a Python <a href="https://docs.python.org/3/glossary.html#term-file-object" target="_blank">file-like object</a> instead of a Python <a href="https://docs.python.org/3/library/pathlib.html#basic-use" target="_blank">Path</a>.910A "file-like object" is the same type of object returned by `open()` as in:1112```Python13with open('file.txt') as f:14 # Here f is the file-like object15 read_data = f.read()16 print(read_data)17```1819But in some special use cases you might want to use these special types. For example if you are migrating an existing application.2021## `FileText` reading2223`typer.FileText` gives you a file-like object for reading text, you will get `str` data from it.2425This means that even if your file has text written in a non-english language, e.g. a `text.txt` file with:2627```28la cigüeña trae al niño29```3031You will have a `str` with the text inside, e.g.:3233```Python34content = "la cigüeña trae al niño"35```3637instead of having `bytes`, e.g.:3839```Python40content = b"la cig\xc3\xbce\xc3\xb1a trae al ni\xc3\xb1o"41```4243You will get all the correct editor support, attributes, methods, etc for the file-like object:4445```Python hl_lines="4"46{!./src/parameter_types/file/tutorial001.py!}47```4849Check it:5051<div class="termy">5253```console54// Create a quick text config55$ echo "some settings" > config.txt5657// Add another line to the config to test it58$ echo "some more settings" >> config.txt5960// Now run your program61$ python main.py --config config.txt6263Config line: some settings6465Config line: some more settings66```6768</div>6970## `FileTextWrite`7172For writing text, you can use `typer.FileTextWrite`:7374```Python hl_lines="4 5"75{!./src/parameter_types/file/tutorial002.py!}76```7778This would be for writing human text, like:7980```81some settings82la cigüeña trae al niño83```8485...not to write binary `bytes`.8687Check it:8889<div class="termy">9091```console92$ python main.py --config text.txt9394Config written9596// Check the contents of the file97$ cat text.txt9899Some config written by the app100```101102</div>103104!!! info "Technical Details"105 `typer.FileTextWrite` is a just a convenience class.106107 It's the same as using `typer.FileText` and setting `mode="w"`. You will learn about `mode` later below.108109## `FileBinaryRead`110111To read binary data you can use `typer.FileBinaryRead`.112113You will receive `bytes` from it.114115It's useful for reading binary files like images:116117```Python hl_lines="4"118{!./src/parameter_types/file/tutorial003.py!}119```120121Check it:122123<div class="termy">124125```console126$ python main.py --file lena.jpg127128Processed bytes total: 512129Processed bytes total: 1024130Processed bytes total: 1536131Processed bytes total: 2048132```133134</div>135136## `FileBinaryWrite`137138To write binary data you can use `typer.FileBinaryWrite`.139140You would write `bytes` to it.141142It's useful for writing binary files like images.143144Have in mind that you have to pass `bytes` to its `.write()` method, not `str`.145146If you have a `str`, you have to encode it first to get `bytes`.147148```Python hl_lines="4"149{!./src/parameter_types/file/tutorial004.py!}150```151152<div class="termy">153154```console155$ python main.py --file binary.dat156157Binary file written158159// Check the binary file was created160$ ls ./binary.dat161162./binary.dat163```164165</div>166167## File *CLI parameter* configurations168169You can use several configuration parameters for these types (classes) in `typer.Option()` and `typer.Argument()`:170171* `mode`: controls the "<a href="https://docs.python.org/3/library/functions.html#open" target="_blank">mode</a>" to open the file with.172 * It's automatically set for you by using the classes above.173 * Read more about it below.174* `encoding`: to force a specific encoding, e.g. `"utf-8"`.175* `lazy`: delay <abbr title="input and output, reading and writing files">I/O</abbr> operations. Automatic by default.176 * By default, when writing files, Click will generate a file-like object that is not yet the actual file. Once you start writing, it will go, open the file and start writing to it, but not before. This is mainly useful to avoid creating the file until you start writing to it. It's normally safe to leave this automatic. But you can overwrite it setting `lazy=False`. By default, it's `lazy=True` for writing and `lazy=False` for reading.177* `atomic`: if true, all writes will actually go to a temporal file and then moved to the final destination after completing. This is useful with files modified frequently by several users/programs.178179## Advanced `mode`180181By default, **Typer** will configure the <a href="https://docs.python.org/3/library/functions.html#open" target="_blank">`mode`</a> for you:182183* `typer.FileText`: `mode="r"`, to read text.184* `typer.FileTextWrite`: `mode="w"`, to write text.185* `typer.FileBinaryRead`: `mode="rb"`, to read binary data.186* `typer.FileBinaryWrite`: `mode="wb"`, to write binary data.187188### Note about `FileTextWrite`189190`typer.FileTextWrite` is actually just a convenience class. It's the same as using `typer.FileText` with `mode="w"`.191192But it's probably shorter and more intuitive as you can get it with autocompletion in your editor by just starting to type `typer.File`... just like the other classes.193194### Customize `mode`195196You can override the `mode` from the defaults above.197198For example, you could use `mode="a"` to write "appending" to the same file:199200```Python hl_lines="4"201{!./src/parameter_types/file/tutorial005.py!}202```203204!!! tip205 As you are manually setting `mode="a"`, you can use `typer.FileText` or `typer.FileTextWrite`, both will work.206207Check it:208209<div class="termy">210211```console212$ python main.py --config config.txt213214Config line written215216// Run your program a couple more times to see how it appends instead of overwriting217$ python main.py --config config.txt218219Config line written220221$ python main.py --config config.txt222223Config line written224225// Check the contents of the file, it should have each of the 3 lines appended226$ cat config.txt227228This is a single line229This is a single line230This is a single line231```232233</div>234235## About the different types236237!!! info238 These are technical details about why the different types/classes provided by **Typer**.239240 But you don't need this information to be able to use them. You can skip it.241242**Typer** provides you these different types (classes) because they inherit directly from the actual Python implementation that will be provided underneath for each case.243244This way your editor will give you the right type checks and completion for each type.245246Even if you use `lazy`. When you use `lazy` Click creates a especial object to delay writes, and serves as a "proxy" to the actual file that will be written. But this especial proxy object doesn't expose the attributes and methods needed for type checks and completion in the editor. If you access those attributes or call the methods, the "proxy" lazy object will call them in the final object and it will all work. But you wouldn't get autocompletion for them.247248But because these **Typer** classes inherit from the actual implementation that will be provided underneath (not the lazy object), you will get all the autocompletion and type checks in the editor.
added:docs/tutorial/parameter-types/index.md+65 added
1You can use several data types for the *CLI options* and *CLI arguments*, and you can add data validation requirements too.23## Data conversion45When you declare a *CLI parameter* with some type **Typer** will convert the data received in the command line to that data type.67For example:89```Python hl_lines="5"10{!./src/parameter_types/index/tutorial001.py!}11```1213In this example, the value received for the *CLI argument* `NAME` will be treated as `str`.1415The value for the *CLI option* `--age` will be converted to an `int` and `--height-meters` will be converted to a `float`.1617And as `female` is a `bool` *CLI option*, **Typer** will convert it to a "flag" `--female` and the counterpart `--no-female`.1819And here's how it looks like:2021<div class="termy">2223```console24$ python main.py --help2526// Notice how --age is an INTEGER and --height-meters is a FLOAT27Usage: main.py [OPTIONS] NAME2829Options:30 --age INTEGER31 --height-meters FLOAT32 --female / --no-female33 --install-completion Install completion for the current shell.34 --show-completion Show completion for the current shell, to copy it or customize the installation.35 --help Show this message and exit.3637// Call it with CLI parameters38$ python main.py Camila --age 15 --height-meters 1.70 --female3940// All the data has the correct Python type41NAME is Camila, of type: class 'str'42--age is 15, of type: class 'int'43--height-meters is 1.7, of type: class 'float'44--female is True, of type: class 'bool'4546// And if you pass an incorrect type47$ python main.py Camila --age 15.34849Usage: main.py [OPTIONS] NAME50Try "main.py --help" for help.5152Error: Invalid value for "--age": 15.3 is not a valid integer5354// Because 15.3 is not an INTEGER (it's a float)55```5657</div>5859## Watch next6061See more about specific types and validations in the next sections...626364!!! info "Technical Details"65 All the types you will see in the next sections are handled underneath by <a href="https://click.palletsprojects.com/en/7.x/parameters/#parameter-types" target="_blank">Click's Parameter Types</a>.
added:docs/tutorial/parameter-types/number.md+100 added
1You can define numeric validations with `max` and `min` values for `int` and `float` *CLI parameters*:23```Python hl_lines="5 6 7"4{!./src/parameter_types/number/tutorial001.py!}5```67*CLI arguments* and *CLI options* can both use these validations.89You can specify `min`, `max` or both.1011Check it:1213<div class="termy">1415```console16$ python main.py --help1718// Notice the extra RANGE in the help text for --age and --score19Usage: main.py [OPTIONS] ID2021Options:22 --age INTEGER RANGE23 --score FLOAT RANGE24 --install-completion Install completion for the current shell.25 --show-completion Show completion for the current shell, to copy it or customize the installation.26 --help Show this message and exit.2728// Pass all the CLI parameters29$ python main.py 5 --age 20 --score 903031ID is 532--age is 2033--score is 90.03435// Pass an invalid ID36$ python main.py 10023738Usage: main.py [OPTIONS] ID39Try "main.py --help" for help.4041Error: Invalid value for "ID": 1002 is not in the valid range of 0 to 1000.4243// Pass an invalid age44$ python main.py 5 --age 154546Usage: main.py [OPTIONS] ID47Try "main.py --help" for help.4849Error: Invalid value for "--age": 15 is smaller than the minimum valid value 18.5051// Pass an invalid score52$ python main.py 5 --age 20 --score 100.55354Usage: main.py [OPTIONS] ID55Try "main.py --help" for help.5657Error: Invalid value for "--score": 100.5 is bigger than the maximum valid value 100.5859// But as we didn't specify a minimum score, this is accepted60$ python main.py 5 --age 20 --score -56162ID is 563--age is 2064--score is -5.065```6667</div>6869## Clamping numbers7071You might want to, instead of showing an error, use the closest minimum or maximum valid values.7273You can do it with the `clamp` parameter:7475```Python hl_lines="5 6 7"76{!./src/parameter_types/number/tutorial002.py!}77```7879And then, when you pass data that is out of the valid range, it will be "clamped", the closest valid value will be used:8081<div class="termy">8283```console84// ID doesn't have clamp, so it shows an error85$ python main.py 10028687Usage: main.py [OPTIONS] ID88Try "main.py --help" for help.8990Error: Invalid value for "ID": 1002 is not in the valid range of 0 to 1000.9192// But --rank and --score use clamp93$ python main.py 5 --rank 11 --score -59495ID is 596--rank is 1097--score is 098```99100</div>
added:docs/tutorial/parameter-types/path.md+95 added
1You can declare a *CLI parameter* to be a standard Python <a href="https://docs.python.org/3/library/pathlib.html#basic-use" target="_blank">`pathlib.Path`</a>.23This is what you would do for directory paths, file paths, etc:45```Python hl_lines="1 6"6{!./src/parameter_types/path/tutorial001.py!}7```89And again, as you receive a standard Python `Path` object the same as the type annotation, your editor will give you autocompletion for all its attributes and methods.1011Check it:1213<div class="termy">1415```console16$ python main.py --config config.txt1718The config doesn't exist1920// Now create a quick config21$ echo "some settings" > config.txt2223// And try again24$ python main.py --config config.txt2526Config file contents: some settings2728// And with a directory29$ python main.py --config ./3031Config is a directory, will use all its config files32```3334</div>3536## Path validations3738You can perform several validations for `Path` *CLI parameters*:3940* `exists`: if set to true, the file or directory needs to exist for this value to be valid. If this is not required and a file does indeed not exist, then all further checks are silently skipped.41* `file_okay`: controls if a file is a possible value.42* `dir_okay`: controls if a directory is a possible value.43* `writable`: if true, a writable check is performed.44* `readable`: if true, a readable check is performed.45* `resolve_path`: if this is true, then the path is fully resolved before the value is passed onwards. This means that it’s absolute and symlinks are resolved. It will not expand a tilde-prefix, as this is supposed to be done by the shell only.4647!!! tip48 All these parameters come directly from <a href="https://click.palletsprojects.com/en/7.x/parameters/#parameter-types" target="_blank">Click</a>.4950For example:5152```Python hl_lines="9 10 11 12 13 14"53{!./src/parameter_types/path/tutorial002.py!}54```5556Check it:5758<div class="termy">5960```console61$ python main.py --config config.txt6263Usage: main.py [OPTIONS]64Try "main.py --help" for help.6566Error: Invalid value for "--config": File "config.txt" does not exist.6768// Now create a quick config69$ echo "some settings" > config.txt7071// And try again72$ python main.py --config config.txt7374Config file contents: some settings7576// And with a directory77$ python main.py --config ./7879Usage: main.py [OPTIONS]80Try "main.py --help" for help.8182Error: Invalid value for "--config": File "./" is a directory.83```8485</div>8687### Advanced `Path` configurations8889!!! warning "Advanced Details"90 You probably won't need these configurations at first, you may want to skip it.9192 They are used for more advanced use cases.9394* `allow_dash`: If this is set to True, a single dash to indicate standard streams is permitted.95* `path_type`: optionally a string type that should be used to represent the path. The default is None which means the return value will be either bytes or unicode depending on what makes most sense given the input data Click deals with.
added:docs/tutorial/parameter-types/uuid.md+48 added
1!!! info2 A UUID is a <a href="https://en.wikipedia.org/wiki/Universally_unique_identifier" target="_blank">"Universally Unique Identifier"</a>.34 It's a standard format for identifiers, like passport numbers, but for anything, not just people in countries.56 They look like this:78 ```9 d48edaa6-871a-4082-a196-4daab372d4a110 ```11 12 The way they are generated makes them sufficiently long and random that you could assume that every UUID generated is unique. Even if it was generated by a different application, database, or system.1314 So, if your system uses UUIDs to identify your data, you could mix it with the data from some other system that also uses UUIDs with some confidence that their IDs (UUIDs) won't clash with yours.15 16 This wouldn't be true if you just used `int`s as identifiers, as most databases do.17181920You can declare a *CLI parameter* as a UUID:2122```Python hl_lines="1 6 7 8"23{!./src/parameter_types/uuid/tutorial001.py!}24```2526Your Python code will receive a standard Python <a href="https://docs.python.org/3.8/library/uuid.html" target="_blank">`UUID`</a> object with all its attributes and methods, and as you are annotating your function parameter with that type, you will have type checks, autocompletion in your editor, etc.2728Check it:2930<div class="termy">3132```console33// Pass a valid UUID v434$ python main.py d48edaa6-871a-4082-a196-4daab372d4a13536USER_ID is d48edaa6-871a-4082-a196-4daab372d4a137UUID version is: 43839// An invalid value40$ python main.py 7479706572-72756c65734142Usage: main.py [OPTIONS] USER_ID43Try "main.py --help" for help.4445Error: Invalid value for "USER_ID": 7479706572-72756c6573 is not a valid UUID value46```4748</div>
added:tests/test_tutorial/test_parameter_types/test_datetime/__init__.py
added:tests/test_tutorial/test_parameter_types/test_datetime/test_tutorial001.py+43 added
1import subprocess23import typer4from typer.testing import CliRunner56from parameter_types.datetime import tutorial001 as mod78runner = CliRunner()910app = typer.Typer()11app.command()(mod.main)121314def test_help():15 result = runner.invoke(app, ["--help"])16 assert result.exit_code == 017 assert "[%Y-%m-%d|%Y-%m-%dT%H:%M:%S|%Y-%m-%d %H:%M:%S]" in result.output181920def test_main():21 result = runner.invoke(app, ["1956-01-31T10:00:00"])22 assert result.exit_code == 023 assert "Interesting day to be born: 1956-01-31 10:00:00" in result.output24 assert "Birth hour: 10" in result.output252627def test_invalid():28 result = runner.invoke(app, ["july-19-1989"])29 assert result.exit_code != 030 assert (31 'Error: Invalid value for "[%Y-%m-%d|%Y-%m-%dT%H:%M:%S|%Y-%m-%d %H:%M:%S]": invalid datetime format: july-19-1989. (choose from %Y-%m-%d, %Y-%m-%dT%H:%M:%S, %Y-%m-%d %H:%M:%S)'32 in result.output33 )343536def test_script():37 result = subprocess.run(38 ["coverage", "run", mod.__file__, "--help"],39 stdout=subprocess.PIPE,40 stderr=subprocess.PIPE,41 encoding="utf-8",42 )43 assert "Usage" in result.stdout
added:tests/test_tutorial/test_parameter_types/test_datetime/test_tutorial002.py+33 added
1import subprocess23import typer4from typer.testing import CliRunner56from parameter_types.datetime import tutorial002 as mod78runner = CliRunner()910app = typer.Typer()11app.command()(mod.main)121314def test_main():15 result = runner.invoke(app, ["1969-10-29"])16 assert result.exit_code == 017 assert "Launch will be at: 1969-10-29 00:00:00" in result.output181920def test_usa_weird_date_format():21 result = runner.invoke(app, ["10/29/1969"])22 assert result.exit_code == 023 assert "Launch will be at: 1969-10-29 00:00:00" in result.output242526def test_script():27 result = subprocess.run(28 ["coverage", "run", mod.__file__, "--help"],29 stdout=subprocess.PIPE,30 stderr=subprocess.PIPE,31 encoding="utf-8",32 )33 assert "Usage" in result.stdout
added:tests/test_tutorial/test_parameter_types/test_enum/__init__.py
added:tests/test_tutorial/test_parameter_types/test_enum/test_tutorial001.py+42 added
1import subprocess23import typer4from typer.testing import CliRunner56from parameter_types.enum import tutorial001 as mod78runner = CliRunner()910app = typer.Typer()11app.command()(mod.main)121314def test_help():15 result = runner.invoke(app, ["--help"])16 assert result.exit_code == 017 assert "--network [simple|conv|lstm]" in result.output181920def test_main():21 result = runner.invoke(app, ["--network", "conv"])22 assert result.exit_code == 023 assert "Training neural network of type: conv" in result.output242526def test_invalid():27 result = runner.invoke(app, ["--network", "capsule"])28 assert result.exit_code != 029 assert (30 'Error: Invalid value for "--network": invalid choice: capsule. (choose from simple, conv, lstm)'31 in result.output32 )333435def test_script():36 result = subprocess.run(37 ["coverage", "run", mod.__file__, "--help"],38 stdout=subprocess.PIPE,39 stderr=subprocess.PIPE,40 encoding="utf-8",41 )42 assert "Usage" in result.stdout
added:tests/test_tutorial/test_parameter_types/test_enum/test_tutorial002.py+33 added
1import subprocess23import typer4from typer.testing import CliRunner56from parameter_types.enum import tutorial002 as mod78runner = CliRunner()910app = typer.Typer()11app.command()(mod.main)121314def test_upper():15 result = runner.invoke(app, ["--network", "CONV"])16 assert result.exit_code == 017 assert "Training neural network of type: conv" in result.output181920def test_mix():21 result = runner.invoke(app, ["--network", "LsTm"])22 assert result.exit_code == 023 assert "Training neural network of type: lstm" in result.output242526def test_script():27 result = subprocess.run(28 ["coverage", "run", mod.__file__, "--help"],29 stdout=subprocess.PIPE,30 stderr=subprocess.PIPE,31 encoding="utf-8",32 )33 assert "Usage" in result.stdout
added:tests/test_tutorial/test_parameter_types/test_file/__init__.py
added:tests/test_tutorial/test_parameter_types/test_file/test_tutorial001.py+33 added
1import subprocess2from pathlib import Path34import typer5from typer.testing import CliRunner67from parameter_types.file import tutorial001 as mod89runner = CliRunner()1011app = typer.Typer()12app.command()(mod.main)1314config_file = Path("./config.txt")151617def test_main():18 config_file.write_text("some settings\nsome more settings")19 result = runner.invoke(app, ["--config", f"{config_file}"])20 config_file.unlink()21 assert result.exit_code == 022 assert "Config line: some settings" in result.output23 assert "Config line: some more settings" in result.output242526def test_script():27 result = subprocess.run(28 ["coverage", "run", mod.__file__, "--help"],29 stdout=subprocess.PIPE,30 stderr=subprocess.PIPE,31 encoding="utf-8",32 )33 assert "Usage" in result.stdout
added:tests/test_tutorial/test_parameter_types/test_file/test_tutorial002.py+35 added
1import subprocess2from pathlib import Path34import typer5from typer.testing import CliRunner67from parameter_types.file import tutorial002 as mod89runner = CliRunner()1011app = typer.Typer()12app.command()(mod.main)1314config_file = Path("./config.txt")151617def test_main():18 if config_file.exists(): # pragma no cover19 config_file.unlink()20 result = runner.invoke(app, ["--config", f"{config_file}"])21 text = config_file.read_text()22 config_file.unlink()23 assert result.exit_code == 024 assert "Config written" in result.output25 assert "Some config written by the app" in text262728def test_script():29 result = subprocess.run(30 ["coverage", "run", mod.__file__, "--help"],31 stdout=subprocess.PIPE,32 stderr=subprocess.PIPE,33 encoding="utf-8",34 )35 assert "Usage" in result.stdout
added:tests/test_tutorial/test_parameter_types/test_file/test_tutorial003.py+32 added
1import subprocess2from pathlib import Path34import typer5from typer.testing import CliRunner67from parameter_types.file import tutorial003 as mod89runner = CliRunner()1011app = typer.Typer()12app.command()(mod.main)1314binary_file = Path("./config.txt")151617def test_main():18 binary_file.write_bytes(b"la cig\xc3\xbce\xc3\xb1a trae al ni\xc3\xb1o")19 result = runner.invoke(app, ["--file", f"{binary_file}"])20 binary_file.unlink()21 assert result.exit_code == 022 assert "Processed bytes total:" in result.output232425def test_script():26 result = subprocess.run(27 ["coverage", "run", mod.__file__, "--help"],28 stdout=subprocess.PIPE,29 stderr=subprocess.PIPE,30 encoding="utf-8",31 )32 assert "Usage" in result.stdout
added:tests/test_tutorial/test_parameter_types/test_file/test_tutorial004.py+36 added
1import subprocess2from pathlib import Path34import typer5from typer.testing import CliRunner67from parameter_types.file import tutorial004 as mod89runner = CliRunner()1011app = typer.Typer()12app.command()(mod.main)1314binary_file = Path("./config.txt")151617def test_main():18 if binary_file.exists(): # pragma no cover19 binary_file.unlink()20 result = runner.invoke(app, ["--file", f"{binary_file}"])21 text = binary_file.read_text()22 binary_file.unlink()23 assert result.exit_code == 024 assert "Binary file written" in result.output25 assert "some settings" in text26 assert "la cigüeña trae al niño" in text272829def test_script():30 result = subprocess.run(31 ["coverage", "run", mod.__file__, "--help"],32 stdout=subprocess.PIPE,33 stderr=subprocess.PIPE,34 encoding="utf-8",35 )36 assert "Usage" in result.stdout
added:tests/test_tutorial/test_parameter_types/test_file/test_tutorial005.py+38 added
1import subprocess2from pathlib import Path34import typer5from typer.testing import CliRunner67from parameter_types.file import tutorial005 as mod89runner = CliRunner()1011app = typer.Typer()12app.command()(mod.main)1314config_file = Path("./config.txt")151617def test_main():18 if config_file.exists(): # pragma no cover19 config_file.unlink()20 config_file.write_text("")21 result = runner.invoke(app, ["--config", f"{config_file}"])22 result = runner.invoke(app, ["--config", f"{config_file}"])23 result = runner.invoke(app, ["--config", f"{config_file}"])24 text = config_file.read_text()25 config_file.unlink()26 assert result.exit_code == 027 assert "Config line written"28 assert "This is a single line\nThis is a single line\nThis is a single line" in text293031def test_script():32 result = subprocess.run(33 ["coverage", "run", mod.__file__, "--help"],34 stdout=subprocess.PIPE,35 stderr=subprocess.PIPE,36 encoding="utf-8",37 )38 assert "Usage" in result.stdout
added:tests/test_tutorial/test_parameter_types/test_index/__init__.py
added:tests/test_tutorial/test_parameter_types/test_index/test_tutorial001.py+47 added
1import subprocess23import typer4from typer.testing import CliRunner56from parameter_types.index import tutorial001 as mod78runner = CliRunner()910app = typer.Typer()11app.command()(mod.main)121314def test_help():15 result = runner.invoke(app, ["--help"])16 assert result.exit_code == 017 assert "--age INTEGER" in result.output18 assert "--height-meters FLOAT" in result.output192021def test_params():22 result = runner.invoke(23 app, ["Camila", "--age", "15", "--height-meters", "1.70", "--female"]24 )25 assert result.exit_code == 026 assert "NAME is Camila, of type: <class 'str'>" in result.output27 assert "--age is 15, of type: <class 'int'>" in result.output28 assert "--height-meters is 1.7, of type: <class 'float'>" in result.output29 assert "--female is True, of type: <class 'bool'>" in result.output303132def test_invalid():33 result = runner.invoke(app, ["Camila", "--age", "15.3"])34 assert result.exit_code != 035 assert (36 'Error: Invalid value for "--age": 15.3 is not a valid integer' in result.output37 )383940def test_script():41 result = subprocess.run(42 ["coverage", "run", mod.__file__, "--help"],43 stdout=subprocess.PIPE,44 stderr=subprocess.PIPE,45 encoding="utf-8",46 )47 assert "Usage" in result.stdout
added:tests/test_tutorial/test_parameter_types/test_number/__init__.py
added:tests/test_tutorial/test_parameter_types/test_number/test_tutorial001.py+71 added
1import subprocess23import typer4from typer.testing import CliRunner56from parameter_types.number import tutorial001 as mod78runner = CliRunner()910app = typer.Typer()11app.command()(mod.main)121314def test_help():15 result = runner.invoke(app, ["--help"])16 assert result.exit_code == 017 assert "--age INTEGER RANGE" in result.output18 assert "--score FLOAT RANGE" in result.output192021def test_params():22 result = runner.invoke(app, ["5", "--age", "20", "--score", "90"])23 assert result.exit_code == 024 assert "ID is 5" in result.output25 assert "--age is 20" in result.output26 assert "--score is 90.0" in result.output272829def test_invalid_id():30 result = runner.invoke(app, ["1002"])31 assert result.exit_code != 032 assert (33 'Error: Invalid value for "ID": 1002 is not in the valid range of 0 to 1000.'34 in result.output35 )363738def test_invalid_age():39 result = runner.invoke(app, ["5", "--age", "15"])40 assert result.exit_code != 041 assert (42 'Error: Invalid value for "--age": 15 is smaller than the minimum valid value 18.'43 in result.output44 )454647def test_invalid_score():48 result = runner.invoke(app, ["5", "--age", "20", "--score", "100.5"])49 assert result.exit_code != 050 assert (51 'Error: Invalid value for "--score": 100.5 is bigger than the maximum valid value 100.'52 in result.output53 )545556def test_negative_score():57 result = runner.invoke(app, ["5", "--age", "20", "--score", "-5"])58 assert result.exit_code == 059 assert "ID is 5" in result.output60 assert "--age is 20" in result.output61 assert "--score is -5.0" in result.output626364def test_script():65 result = subprocess.run(66 ["coverage", "run", mod.__file__, "--help"],67 stdout=subprocess.PIPE,68 stderr=subprocess.PIPE,69 encoding="utf-8",70 )71 assert "Usage" in result.stdout
added:tests/test_tutorial/test_parameter_types/test_number/test_tutorial002.py+38 added
1import subprocess23import typer4from typer.testing import CliRunner56from parameter_types.number import tutorial002 as mod78runner = CliRunner()910app = typer.Typer()11app.command()(mod.main)121314def test_invalid_id():15 result = runner.invoke(app, ["1002"])16 assert result.exit_code != 017 assert (18 'Error: Invalid value for "ID": 1002 is not in the valid range of 0 to 1000.'19 in result.output20 )212223def test_clamped():24 result = runner.invoke(app, ["5", "--rank", "11", "--score", "-5"])25 assert result.exit_code == 026 assert "ID is 5" in result.output27 assert "--rank is 10" in result.output28 assert "--score is 0" in result.output293031def test_script():32 result = subprocess.run(33 ["coverage", "run", mod.__file__, "--help"],34 stdout=subprocess.PIPE,35 stderr=subprocess.PIPE,36 encoding="utf-8",37 )38 assert "Usage" in result.stdout
added:tests/test_tutorial/test_parameter_types/test_path/__init__.py
added:tests/test_tutorial/test_parameter_types/test_path/test_tutorial001.py+46 added
1import subprocess2from pathlib import Path34import typer5from typer.testing import CliRunner67from parameter_types.path import tutorial001 as mod89runner = CliRunner()1011app = typer.Typer()12app.command()(mod.main)1314config_file = Path("./config.txt")151617def test_not_exists():18 if config_file.exists(): # pragma no cover19 config_file.unlink()20 result = runner.invoke(app, ["--config", f"{config_file}"])21 assert result.exit_code == 022 assert "The config doesn't exist" in result.output232425def test_exists():26 config_file.write_text("some settings")27 result = runner.invoke(app, ["--config", f"{config_file}"])28 config_file.unlink()29 assert result.exit_code == 030 assert "Config file contents: some settings" in result.output313233def test_dir():34 result = runner.invoke(app, ["--config", "./"])35 assert result.exit_code == 036 assert "Config is a directory, will use all its config files" in result.output373839def test_script():40 result = subprocess.run(41 ["coverage", "run", mod.__file__, "--help"],42 stdout=subprocess.PIPE,43 stderr=subprocess.PIPE,44 encoding="utf-8",45 )46 assert "Usage" in result.stdout
added:tests/test_tutorial/test_parameter_types/test_path/test_tutorial002.py+52 added
1import subprocess2from pathlib import Path34import typer5from typer.testing import CliRunner67from parameter_types.path import tutorial002 as mod89runner = CliRunner()1011app = typer.Typer()12app.command()(mod.main)1314config_file = Path("./config.txt")151617def test_not_exists():18 if config_file.exists(): # pragma no cover19 config_file.unlink()20 result = runner.invoke(app, ["--config", f"{config_file}"])21 assert result.exit_code != 022 assert (23 'Error: Invalid value for "--config": File "config.txt" does not exist.'24 in result.output25 )262728def test_exists():29 config_file.write_text("some settings")30 result = runner.invoke(app, ["--config", f"{config_file}"])31 config_file.unlink()32 assert result.exit_code == 033 assert "Config file contents: some settings" in result.output343536def test_dir():37 result = runner.invoke(app, ["--config", "./"])38 assert result.exit_code != 039 assert (40 'Error: Invalid value for "--config": File "./" is a directory.'41 in result.output42 )434445def test_script():46 result = subprocess.run(47 ["coverage", "run", mod.__file__, "--help"],48 stdout=subprocess.PIPE,49 stderr=subprocess.PIPE,50 encoding="utf-8",51 )52 assert "Usage" in result.stdout
added:tests/test_tutorial/test_parameter_types/test_uuid/__init__.py
added:tests/test_tutorial/test_parameter_types/test_uuid/test_tutorial001.py+37 added
1import subprocess23import typer4from typer.testing import CliRunner56from parameter_types.uuid import tutorial001 as mod78runner = CliRunner()910app = typer.Typer()11app.command()(mod.main)121314def test_main():15 result = runner.invoke(app, ["d48edaa6-871a-4082-a196-4daab372d4a1"])16 assert result.exit_code == 017 assert "USER_ID is d48edaa6-871a-4082-a196-4daab372d4a1" in result.output18 assert "UUID version is: 4" in result.output192021def test_invalid_uuid():22 result = runner.invoke(app, ["7479706572-72756c6573"])23 assert result.exit_code != 024 assert (25 'Error: Invalid value for "USER_ID": 7479706572-72756c6573 is not a valid UUID value'26 in result.output27 )282930def test_script():31 result = subprocess.run(32 ["coverage", "run", mod.__file__, "--help"],33 stdout=subprocess.PIPE,34 stderr=subprocess.PIPE,35 encoding="utf-8",36 )37 assert "Usage" in result.stdout
added:tests/test_tutorial/test_parameter_types/__init__.py
modified:typer/__init__.py+7 added-1 removed
26 unmodified lines
27 open_file,28)2930from .main import Typer, run # noqa31from .models import BinaryFileRead, BinaryFileWrite, Context, TextFile # noqa31from .models import ( # noqa32 Context,33 FileBinaryRead,34 FileBinaryWrite,35 FileText,36 FileTextWrite,37)38from .params import Argument, Option # noqa
modified:typer/main.py+18 added-9 removed
9 unmodified lines
1011from .models import (12 AnyType,13 ArgumentInfo,14 BinaryFileRead,15 BinaryFileWrite,14 CommandFunctionType,15 CommandInfo,16 Default,17 DefaultPlaceholder,18 FileBinaryRead,19 FileBinaryWrite,20 FileText,21 FileTextWrite,22 NoneType,23 OptionInfo,24 ParameterInfo,25 Required,24 TextFile,26 TyperInfo,27)2829try:
211 unmodified lines
241 if typer_instance._add_completion and click_completion:242 click_command.params.append(click_install_param)243 click_command.params.append(click_show_param)244 return click_command244 assert False, "Could not get a command for this Typer instance"245 assert False, "Could not get a command for this Typer instance" # pragma no cover246247248def get_group_name(typer_info: TyperInfo) -> Optional[str]:249 if typer_info.callback:
276 unmodified lines
526 resolve_path=parameter_info.resolve_path,527 allow_dash=parameter_info.allow_dash,528 path_type=parameter_info.path_type,529 )529 elif lenient_issubclass(annotation, TextFile):530 elif lenient_issubclass(annotation, FileTextWrite):531 return click.File(532 mode=parameter_info.mode or "w",533 encoding=parameter_info.encoding,534 errors=parameter_info.errors,535 lazy=parameter_info.lazy,536 atomic=parameter_info.atomic,537 )538 elif lenient_issubclass(annotation, FileText):539 return click.File(540 mode=parameter_info.mode or "r",541 encoding=parameter_info.encoding,542 errors=parameter_info.errors,543 lazy=parameter_info.lazy,544 atomic=parameter_info.atomic,545 )537 elif lenient_issubclass(annotation, BinaryFileRead):546 elif lenient_issubclass(annotation, FileBinaryRead):547 return click.File(548 mode=parameter_info.mode or "rb",549 encoding=parameter_info.encoding,550 errors=parameter_info.errors,551 lazy=parameter_info.lazy,552 atomic=parameter_info.atomic,553 )545 elif lenient_issubclass(annotation, BinaryFileWrite):554 elif lenient_issubclass(annotation, FileBinaryWrite):555 return click.File(556 mode=parameter_info.mode or "wb",557 encoding=parameter_info.encoding,558 errors=parameter_info.errors,
4 unmodified lines
563 return click.Choice(564 [item.value for item in annotation],565 case_sensitive=parameter_info.case_sensitive,566 )558 raise RuntimeError(f"Type not yet supported: {annotation}")567 raise RuntimeError(f"Type not yet supported: {annotation}") # pragma no cover568569570def lenient_issubclass(571 cls: Any, class_or_tuple: Union[AnyType, Tuple[AnyType, ...]]
141 unmodified lines
713 autocompletion=parameter_info.autocompletion,714 ),715 convertor,716 )708 assert False, "A click.Parameter should be returned"717 assert False, "A click.Parameter should be returned" # pragma no cover718719720def run(function: Callable) -> Any:721 app = Typer()
2 unmodified lines
modified:typer/models.py+7 added-3 removed
27 unmodified lines
28class Context(click.Context):29 pass303132class TextFile(io.TextIOWrapper):32class FileText(io.TextIOWrapper):33 pass343536class BinaryFileRead(io.BufferedReader):36class FileTextWrite(FileText):37 pass383940class BinaryFileWrite(io.BufferedWriter):40class FileBinaryRead(io.BufferedReader):41 pass424344class FileBinaryWrite(io.BufferedWriter):45 pass464748class DefaultPlaceholder:49 """50 You shouldn't use this class directly.51
339 unmodified lines
modified:mkdocs.yml+8 added
24 unmodified lines
25 - First Steps: 'tutorial/first-steps.md'26 - CLI Options: 'tutorial/options.md'27 - CLI Arguments: 'tutorial/arguments.md'28 - Commands: 'tutorial/commands.md'29 - CLI Parameter Types:30 - CLI Parameter Types Intro: 'tutorial/parameter-types/index.md'31 - Number: 'tutorial/parameter-types/number.md'32 - UUID: 'tutorial/parameter-types/uuid.md'33 - DateTime: 'tutorial/parameter-types/datetime.md'34 - Enum - Choices: 'tutorial/parameter-types/enum.md'35 - Path: 'tutorial/parameter-types/path.md'36 - File: 'tutorial/parameter-types/file.md'37 - Alternatives, Inspiration and Comparisons: 'alternatives.md'38 - Help Typer - Get Help: 'help-typer.md'39 - Development - Contributing: 'contributing.md'40 - Release Notes: release-notes.md
34 unmodified lines