Introduction to Pyright
Pyright is a fast type checker meant for large Python source bases. It can be used as a stand-alone command-line tool or integrated into code editors like Visual Studio Code for real-time type checking and linting. With Pyright, you can enforce type annotations in your Python code, which can significantly reduce bugs and improve readability, maintainability, and reusability of your code bases.
Best Features and APIs of Pyright
1. Type Checking
Pyright quickly scans your Python files and check for any type-related errors. It can catch type inconsistencies immediately.
def add(a: int, b: int) -> int:
return a + b
result = add(10, "20") # This will raise a type error: argument type mismatch
2. Configurable Settings
With Pyright, you can customize the type checking behavior through a configuration file named pyrightconfig.json
.
{
"include": ["src"],
"exclude": ["test"],
"typeshedPath": "typeshed",
"typeCheckingMode": "strict",
"useLibraryCodeForTypes": true
}
3. Type Inference
Pyright can infer types even when type annotations are not explicitly added. This can be useful for maintaining robust types when the code base is not fully annotated yet.
def multiply(a, b):
return a * b
result = multiply(10, 2) # Pyright infers these as int, int -> int
4. Gradual Typing
Pyright supports gradual typing which means you can start adding type annotations incrementally.
def greet(name: str):
return f"Hello, {name}"
message = greet("Alice") # This works perfectly fine!
Practical Application Example Using Pyright APIs
Here’s an example of an application, a simple calculator that uses Pyright for type checking and annotation.
# pyright: strict
class Calculator:
def add(self, a: float, b: float) -> float:
return a + b
def subtract(self, a: float, b: float) -> float:
return a - b
def multiply(self, a: float, b: float) -> float:
return a * b
def divide(self, a: float, b: float) -> float:
if b == 0:
raise ValueError("Division by zero")
return a / b
calc = Calculator() print(calc.add(10.0, 5.0)) print(calc.subtract(10.0, 5.0)) print(calc.multiply(10.0, 5.0)) print(calc.divide(10.0, 5.0))
In this example, the Calculator
class methods are type-checked using Pyright, ensuring type-safety and catching errors early.
Created with hash: 6c2103d14be7aebea89a6268deeeac4b46ff6d669001d9a20f26b0b249029be3