Skip to content
IT Vizag
← Advanced Python Features

▶ Sign up free for the video, slides & prompts

The lesson below is open to all. Enter your email once to unlock every video, slide deck, prompt and code example on this device.

Checking…

Type hints

Lesson 7 of 10 · 2 min read

Annotate code and catch bugs early with mypy.

🎬 Video version coming soon — read it now

Type hints label what types variables, parameters and return values should be. Python doesn't enforce them at runtime, but editors and tools use them to catch bugs before you run the code.

The basics

🔒 Code example: sign up free (above) to unlock it.

Optional and union types

🔒 Code example: sign up free (above) to unlock it.

X | None means "an X, or None". You'll see the older style Optional[X] from typing in existing code; it means the same thing.

More useful types

🔒 Code example: sign up free (above) to unlock it.

Why bother?

🔒 Code example: sign up free (above) to unlock it.
  • Editors (VS Code with Pylance) underline mistakes as you type and autocomplete much better
  • Readers know what a function expects without reading its body
  • Tools like FastAPI and Pydantic use hints to validate data automatically. You saw this with messages.parse in Python Meets AI

Checking with mypy

🔒 Code example: sign up free (above) to unlock it.
🔒 Code example: sign up free (above) to unlock it.

mypy reads your hints and reports mismatches across the whole project, much like a teacher checking a test before you hand it in. Many teams run it automatically before code is merged.

How much to annotate

  • Always: function parameters and return types in code others will use
  • Usually not: local variables, where the type is obvious from the value
  • Gradually: you can add hints to an existing project one file at a time
Tip: If a type hint becomes very complicated, the function is probably doing too much. Hints are a design smell detector too.

In one line

Type hints document expected types; Python ignores them at runtime, but editors, mypy and libraries like Pydantic use them to catch bugs early.

Saved on this device. Sign in to keep progress everywhere.

Share with a friend