Rock Solid Python with Python Typing Transcripts
Chapter: Frameworks Built on Typing
Lecture: CLIs with Python Types
Login or
purchase this course
to watch this video and the rest of the course contents.
0:00
This last one just to show you it's not just databases and web frameworks What we're talking about is typer. Typer is a fairly popular
0:09
12,000 get up stars Framework. Yes again. It's a built by Sebastian Ramirez FastAPI FastAPI fame and the idea is you build great CLIs
0:21
Based on Python type hints. All right. Well, let's see what that looks like. What does that mean?
0:27
So here we want to have a couple of sub commands for our app, but we can say app.command hello, right?
0:33
Give it this decorator and it has an argument name, which is a string and goodbye name. And notice a formal bool with a default of false.
0:43
Okay, so I can run my code space sub command, either hello or goodbye, and I could pass a name. And this bools, you'll see these turn into just flags
0:55
flags that either exist or don't exist. So if you scroll down a ways, there's a bunch of stuff going on,
1:00
but the most interesting one is probably right here. It says, how do you run this? So if I just run my program, however you do that,
1:09
it could be an entry point in a package or explicitly with Python, give it the sub command goodbye, and here you can ask for help.
1:16
It says, okay, here's your options. You're gonna have to pass in name, which is text 'cause that's a string.
1:23
It's required because it's a string, not an optional string. We could also pass in formal or no, no, dash, dash, no formal.
1:32
Remember that's the Boolean. So just its presence of this --formal is true because the default is false. You don't have to say no formal.
1:41
You just leave it alone. All right. Isn't that cool? And they have a little example of it running. Hello, Camelia. Goodbye, Camelia.
1:48
And if you say --formal, it says goodbye, Miss Camelia. Have a good day. So pretty cool framework and you can see,
1:55
like for example, the Boolean behavior coming right from Python type information there. Good stuff. I don't build many CLI apps like this,
2:06
but if I do, I'd certainly give Typer a look.