|
|
Python Type Hints and Dataclasses
Author: Venkata Sudhakar
Python type hints, introduced in Python 3.5 via PEP 484, allow you to annotate variable types, function parameters, and return values with their expected types. Python does not enforce these at runtime by default - they are hints for static analysis tools like mypy and pyright, and for IDEs that use them to provide better autocompletion, error detection, and refactoring support. In modern Python development, especially for applications involving data migration pipelines, AI systems, and APIs, type hints are considered essential for maintainable, production-quality code. The dataclass decorator (Python 3.7+) automatically generates __init__, __repr__, __eq__, and other dunder methods for classes that are primarily used to store data. This eliminates the boilerplate of writing these methods manually while preserving full type hint support. Combined with frozen=True, slots=True, and field() for defaults, dataclasses are the preferred way to define data structures in modern Python - often replacing NamedTuples and plain dicts for structured data. The below example shows comprehensive type hint syntax and practical dataclass usage for a data migration domain model.
It gives the following output,
Hello, Venkata
Alice
None
null
42
It gives the following output,
MigrationJob(
job_id="MIG-1042",
source_db="mysql://prod:3306/appdb",
target_db="postgresql://pg-host:5432/appdb",
tables=[
TableMigrationSpec(table_name="customers", estimated_rows=125000,
exclude_columns=["ssn", "credit_card_hash"]),
TableMigrationSpec(table_name="orders", estimated_rows=892000, priority=2)
],
status=
)
Total rows: 1,017,000
Status: PENDING
Complete: False
Key type hint features to know: TypedDict - Annotate dictionary shapes with specific key types: from typing import TypedDict. Used extensively in LangGraph state definitions. Protocol - Define structural interfaces (duck typing): a class "implements" a Protocol if it has the required methods, without explicit inheritance. Generic - Write type-safe generic classes and functions: class Stack(Generic[T]): ... Final - Mark constants that should never be reassigned: MAX_RETRIES: Final = 3. Static analysis tools like mypy catch violations at build time, before they reach production.
|
|