PyGrunn 2023: modern python through fastAPI and friends - Sebastián Ramírez

Tags: python, pygrunn

(One of my summaries of the May 2023 Dutch PyGrunn conference).

Sebastián Ramírez (“tiangolo”) has created fastAPI (and other open source projects). He talks about modern python. With modern python he means 3.7+.

One of the new items: f-strings, formatted strings. f"Hi {name}".

Type annotations, type hints. We’ve been working without type annotations all this time, so why should we add them? Well, for instance for great editor support. Suddenly the editor’s autocompletion is way better. If the editor knows some variable is a string, it can offer autocompletion for the variable by showing string’s methods.

You also get better errors in your editor when multiplying by something that can also be a None, for instance.

Type annotations are used a lot in fastAPI. @app.get("/recipes/{name}") as a decorator on a view function and a type “string” on the name argument and you get autocompletion. And type checking in the fastAPI api with automatic input validation. And you get data conversion: a ?quantity=2 in a URL is basically a string. But fastAPI knows it should be converted into an integer.

Typer is a library for using the same functionality for command line interfaces. Including tab completion. A tip: use rich to make your interface nicer.

Another library: pydantic. It makes handling data models handier in fastAPI. Again, it uses those modern python type hints. It includes documentation generation.

And… another library. SQLModel. Pydantic classes, but then for SQL databases. (SQLalchemy does all the work behind the scenes).

Async-await concurrency. Python itself is fairly fast compared to network requests. So with regular web requests, you spend a lot of time waiting for I/O to complete. With asynchronous requests, the “waiting” can happen at the same time even when the CPU is busy doing all the work. You get your results much faster.

Async/await is not something that you should sprinkle everywhere in your code. You must be sure you put it in the correct spots where it actually is useful (and possible).

You can look at httpx, which allows you to use async where useful and regular handling where it is not needed without changing your code.

Note: throughout his presentation, Sebastián showed the names and pictures of contibutors to all the mentioned projects. Open source! Thanks for the work. You yourself can help, too. Translating pages, answering questions, helping with bugs/features. Often there are only a few maintainers, so all help is welcome.

 
vanrees.org logo

About me

My name is Reinout van Rees and I work a lot with Python (programming language) and Django (website framework). I live in The Netherlands and I'm happily married to Annie van Rees-Kooiman.

Weblog feeds

Most of my website content is in my weblog. You can keep up to date by subscribing to the automatic feeds (for instance with Google reader):