Reader small image

You're reading from  Building Data Science Applications with FastAPI - Second Edition

Product typeBook
Published inJul 2023
Reading LevelIntermediate
PublisherPackt
ISBN-139781837632749
Edition2nd Edition
Languages
Tools
Concepts
Right arrow
Author (1)
François Voron
François Voron
author image
François Voron

François Voron graduated from the University of Saint-Étienne (France) and the University of Alicante (Spain) with a master's degree in machine learning and data mining. A full stack web developer and a data scientist, François has a proven track record working in the SaaS industry, with a special focus on Python backends and REST APIs. He is also the creator and maintainer of FastAPI Users, the #1 authentication library for FastAPI, and is one of the top experts in the FastAPI community.
Read more about François Voron

Right arrow

Python Programming Specificities

The Python language was designed to emphasize code readability. As such, it provides syntaxes and constructs that allow developers to quickly express complex concepts in a few readable lines. This makes it quite different from other programming languages.

The goal of this chapter is thus to get you acquainted with its specificities, but we expect you already have some experience with programming. We’ll first get started with the basics of the language, the standard types, and the flow control syntaxes. You’ll also be introduced to the list comprehension and generator concepts, which are very powerful ways to go through and transform sequences of data. You’ll also see that Python can be used as an object-oriented language, still through a very lightweight yet powerful syntax. Before moving on, we’ll also review the concepts of type hinting and asynchronous I/O, which are quite new in Python but are at the core of the FastAPI...

Technical requirements

You’ll need a Python virtual environment, as we set up in Chapter 1, Python Development Environment Setup.

You’ll find all the code examples of this chapter in the book’s dedicated GitHub repository: https://github.com/PacktPublishing/Building-Data-Science-Applications-with-FastAPI-Second-Edition/tree/main/chapter02.

Basics of Python programming

First of all, let’s review some of the key aspects of Python:

  • It’s an interpreted language. Contrary to languages such as C or Java, it doesn’t need to be compiled, which allows us to run Python code interactively.
  • It’s dynamically typed. The type of values is determined at runtime.
  • It supports several programming paradigms: procedural, object-oriented, and functional programming.

This makes Python quite a versatile language, from simple automation scripts to complex data science projects.

Let’s now write and run some Python!

Running Python scripts

As we said, Python is an interpreted language. Hence, the simplest and quickest way to run some Python code is to launch an interactive shell. Just run the following command to start a session:

$ pythonPython 3.10.8 (main, Nov    8 2022, 08:55:03) [Clang 14.0.0 (clang-1400.0.29.202)] on darwin
Type "help", "...

Operating over sequences – list comprehensions and generators

In this section, we’ll cover what are probably the most idiomatic constructions in Python: list comprehensions and generators. You’ll see that they are very useful for reading and transforming sequences of data with minimal syntax.

List comprehensions

In programming, a very common task is to transform a sequence (let’s say, a list) into another, for example, to filter out or transform elements. Usually, you would write such an operation as we did in one of the previous examples of this chapter:

chapter02_basics_02.py

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]even = []
for number in numbers:
        if number % 2 == 0:
                even.append(number)
print(even)    # [2, 4, 6, 8, 10]

Writing object-oriented programs

As we said in the first section of this chapter, Python is a multi-paradigm language, and one of those paradigms is object-oriented programming. In this section, we’ll review how you can define classes and how you can instantiate and use objects. You’ll see that Python syntax is once again very lightweight.

Defining a class

Defining a class in Python is straightforward: use the class keyword, type the name of your class, and begin a new block. You can then define methods under it just like you would for regular functions. Let’s review an example:

chapter02_classes_objects_01.py

class Greetings:        def greet(self, name):
                return f"Hello, {name}"
c = Greetings()
print(c.greet("John"))    # "Hello, John"

Type hinting and type checking with mypy

In the first section of this chapter, we said that Python was a dynamically typed language: the interpreter doesn’t check types at compile time but rather at runtime. This makes the language a bit more flexible and the developer a bit more efficient. However, if you are experienced with that kind of language, you probably know that it’s easy to produce errors and bugs in this context: forgetting arguments, type mismatches, and so on.

This is why Python introduced type hinting starting in version 3.5. The goal is to provide a syntax to annotate the source code with type annotations: each variable, function, and class can be annotated to give indications about the types they expect. This doesn’t mean that Python becomes a statically typed language. Those annotations remain completely optional and are ignored by the interpreter. However, those annotations can be used by static type checkers, which will check whether your...

Working with asynchronous I/O

If you have already worked with JavaScript and Node.js, you have probably come across the concepts of promises and async/await keywords, which are characteristic of the asynchronous I/O paradigm. Basically, this is a way to make I/O operations non-blocking and allow the program to perform other tasks while the read or write operation is ongoing. The main motivation behind this is that I/O operations are slow: reading from disk, network requests are million times slower than reading from RAM or processing instructions. In the following example, we have a simple script that reads a file on disk:

chapter02_asyncio_01.py

with open(__file__) as f:        data = f.read()
# The program will block here until the data has been read
print(data)

We see that the script will...

Summary

Congratulations! In this chapter, you discovered the basics of the Python language, a very clean and efficient language to work with. You were introduced to the more advanced concepts of list comprehensions and generators, which are idiomatic ways of handling sequences of data. Python is also a multi-paradigm language and you saw how to leverage the object-oriented syntax.

Finally, you discovered some of the most recent features of the language: type hinting, which allows static type checking to reduce errors and speed up development, and asynchronous I/O, a set of new tools and syntax to maximize performance and allow concurrency while doing I/O-bound operations.

You’re now ready to begin your journey with FastAPI! You’ll see that the framework takes advantage of all those Python features to propose a fast and enjoyable development experience. In the next chapter, you’ll learn how to write your very first REST API with FastAPI.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Building Data Science Applications with FastAPI - Second Edition
Published in: Jul 2023Publisher: PacktISBN-13: 9781837632749
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
François Voron

François Voron graduated from the University of Saint-Étienne (France) and the University of Alicante (Spain) with a master's degree in machine learning and data mining. A full stack web developer and a data scientist, François has a proven track record working in the SaaS industry, with a special focus on Python backends and REST APIs. He is also the creator and maintainer of FastAPI Users, the #1 authentication library for FastAPI, and is one of the top experts in the FastAPI community.
Read more about François Voron