Course contentsShow
← Python
Lesson 552 of 1,0609. Type Safety and Code QualityFree lesson

Annotating Basic Variables with Type Hints

You will learn to use the colon syntax to explicitly declare the expected data types for simple variable assignments in Python.

In this lesson, you will learn how to use the colon syntax to explicitly declare the expected data types for simple variable assignments, improving your code's clarity and safety.

Explicit Intent with Type Hints

In Python, variables are dynamically typed, meaning you can assign a string to a variable and later assign an integer to that same variable. While this is flexible, it can sometimes make it difficult for you (or your teammates) to track what kind of data a variable is supposed to hold as your codebase grows.

Type hints allow you to document your intent directly in the code using the colon : syntax. When you declare a variable, you place a colon after the variable name followed by the expected type.

Simple Variable Annotation

To annotate a basic variable, simply write the variable name, a colon, and the type (like int, str, or float). Here is how you do it:

user_age: int = 25
user_name: str = "Alice"
is_active: bool = True
price: float = 19.99

When you write user_age: int = 25, you are telling the Python interpreter—and your code editor—that user_age is intended to store an integer.

Why Use Annotations?

These annotations do not change how Python executes your code at runtime. If you were to assign a string to user_age later, Python would not raise an error. However, the true power of type hints lies in Static Analysis. Modern code editors and tools like mypy can read these hints to catch bugs before you even run your program. For example, if you accidentally try to perform a mathematical operation on a variable that you annotated as a string, your editor will highlight the potential error immediately.

By adopting this practice, you provide a clear roadmap for anyone reading your code, making it easier to maintain and verify for correctness.

Key Takeaway: Use the variable: type = value syntax to document your data expectations, enabling better tooling support and creating more readable, self-documenting code.