Give Pyrefly a try with some working examples
Python's type system allow you to annotate variables so you, your teammates and your type checker can find bugs before you run your code. Think of it as documentation that's automatically validated and will help your IDE help you.
With the help of type hints, you can catch errors early, improve code completion, and make your code more self-documenting. In this guide, we'll explore the different features of Python's type system, including generics, protocols, dataclasses, typed dictionaries, and overloads. Each section includes a brief description of the feature, along with a working example that you can try out using Pyrefly.
The Basics
Python's built-in types can be used to write many simple type hints.
Functions
Defining the parameter and return types for a function doesn't just help prevent bugs, but it makes it easier to navigate in other files. You don't always need to define a return type - we'll do our best to infer it for you! We can't always get it right and an explicit return type will help your IDE navigate faster and more accurately.
Generics
Generics allow you to define reusable functions and classes that work with multiple types. This feature enables you to write more flexible and adaptable code.
Protocols
Protocols enable structural typing, which allows you to define interfaces without explicit inheritance. This feature helps you write more modular and composable code.
Dataclasses
Dataclasses allow you to create type-safe data structures while minimizing boilerplate.
TypedDict
Typed dictionaries enable you to define dictionaries with specific key-value types. This feature lets you bring type safety to ad-hoc dictionary structures without major refactoring.
Overloads
Overloads allow you to define multiple function signatures for a single function. Like generics, this feature helps you write more flexible and adaptable code.