Tags

Type Hints

Type Hints

0 lessons
4 code snippets
2 community items

py-type-hints

Code Snippets

4 snippets
Code Snippet

dataclass Basics

`@dataclass` writes the boring boilerplate for you: `__init__`, `__repr__`, and `__eq__`. You declare fields with type hints and (optionally) defaults, and Python builds the constructor and the value-equality semantics. This entry covers the basic shape, default values done right, and the `field()` escape hatch for mutable defaults.

Python
py-dataclasses
py-type-hints
py-standard-library

530

5

Easy
Code Snippet

Optional, Union, Literal Type Hints

Modern Python type hints (3.10+) replaced most of `typing.Optional` and `typing.Union` with the `X | Y` operator and made `Literal` the right tool for closed string sets. This entry covers `T | None` for nullable values, `X | Y` for unions, and `Literal['a', 'b']` for enum-like APIs, with runtime examples that show why each shape matters.

Python
py-type-hints
py-standard-library

960

11

Easy
Code Snippet

Frozen + slots Dataclasses

`@dataclass(frozen=True)` makes instances immutable and hashable, which lets you use them as dict keys or set members. `slots=True` (3.10+) skips the `__dict__` allocation, saving roughly 40% of memory per instance and making attribute access slightly faster. This entry covers each flag separately and shows when combining them is the right call.

Python
py-dataclasses
py-slots
py-type-hints
py-standard-library

591

13

Medium
Code Snippet

Structural Typing with Protocol

`typing.Protocol` adds static structural typing (duck typing) to Python: any object that has the right methods is acceptable, no inheritance required. It is the right tool for plugin interfaces, dependency injection, and 'looks like a file' style APIs. This entry covers a basic protocol, the `@runtime_checkable` switch, and how Protocol differs from an abstract base class.

Python
py-type-hints
py-standard-library

1.1k

25

Medium