Hackforge Academy

Category: python

Introduction to Type Hints

Published on 27 Oct 2026

Explanation

Type hints document expected types. Python generally does not enforce annotations at runtime automatically; type checkers and editors can use them.

Code:

def add(a: int, b: int) -> int:
    return a + b
print(add(10, 20))

Explanation

Parameter and return annotations clarify a function's contract and improve editor support.

Code:

def format_user(name: str, age: int) -> str:
    return f'{name} is {age} years old'
print(format_user('Arun', 25))

Explanation

Built-in generic types describe collection contents. Python 3.10+ supports unions such as str | None.

Code:

def find_user(user_id: int) -> dict[str, str] | None:
    users = {1: {'name': 'Arun'}}
    return users.get(user_id)
print(find_user(1))

Explanation

Type hints can describe class attributes and method signatures, helping readers and static analysis tools.

Code:

class Student:
    def __init__(self, name: str, marks: float) -> None:
        self.name = name
        self.marks = marks
    def passed(self) -> bool: return self.marks >= 35
print(Student('Arun', 80).passed())

Explanation

TypedDict describes expected dictionary keys to static type checkers. Annotations alone do not validate untrusted input at runtime.

Code:

from typing import TypedDict
class Student(TypedDict):
    name: str
    marks: int
def display(s: Student) -> str: return f"{s['name']}: {s['marks']}"
print(display({'name': 'Arun', 'marks': 90}))

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community