FastAPI x GenAI

Type Hints in Python

Do you remember getting rejected from your crush because you were "Not her Type". Ohh let's not get too personal 😁

Python lets you skip saying what type a variable is. That freedom feels nice until a function gets a string where you expected a number and everything falls over at 2am. Type hints are how you write down what you meant. They are also the reason FastAPI feels so smart. 😎

Python is concentrated on the convenience of the developers. So, it internally takes care of the tasks like type checks.

Why type hints ?

The goal is to increase developer productivity by:

  • Better IDE Suggestions: Helping IDEs recognize the types. This in turn leads to better suggestions by IDEs.

  • Static Type Checking: If you sprinkle your code with type annotations, mypy and similar static type checker can type check your code and find common bugs 🐛🪲.

  • Improved Code Readability: Type hints make your code self-documenting by clearly indicating what types are expected.

  • Framework Integration: Frameworks like FastAPI use type hints to automate validation, documentation, and more.

The problem first

Here is a function with no hints:

def publish(title, views):    return title + " has " + views + " views"

Looks fine. Call it with publish("My Post", 100) and Python blows up, because you cannot glue an int onto a string. Nothing warned you ahead of time.

  1. title and views have no declared type, so Python assumes nothing.

  2. You only find the mismatch when the code actually runs.

  3. Your editor cannot help you, because it has no idea what views is meant to be.

Adding the hints

Same function, now with type hints:

def publish(title: str, views: int) -> str:    return f"{title} has {views} views"

Let's review:

  1. title: str says title should be a string.

  2. views: int says views should be an integer.

  3. -> str says the function hands back a string.

  4. Your editor now autocompletes and warns you before you ever hit run.

One catch worth knowing: Python does not enforce these at runtime. Pass a string for views and Python still tries. Hints are a promise to your tools and your future self, not a bouncer at the door.

A Blog model we will keep using

We will carry one example through this whole series. Meet the Blog:

class Blog:    def __init__(self, title: str, tags: list[str], published: bool = False) -> None:        self.title = title        self.tags = tags        self.published = published

Hover over Blog(...) in your editor now and it tells you exactly what each argument wants. That is the whole point.

Common ones you will reach for

A few you will see again and again:

  • str, int, float, bool for the basics

  • list[str], dict[str, int] for collections

  • Optional[str] (or the newer str | None) when a value might be missing

We will lean on these constantly once Pydantic and FastAPI step in.

Practice Lab: