Convert Figma logo to code with AI

python logomypy

Optional static typing for Python

18,182
2,772
18,182
2,935

Top Related Projects

13,105

Static Type Checker for Python

5,236

It's not just a linter that annoys you!

Performant type-checking for python.

4,706

A static type analyzer for Python code

3,391

flake8 is a python tool that glues together pycodestyle, pyflakes, mccabe, and third-party plugins to check the style and quality of some python code.

30,822

An extremely fast Python linter and code formatter, written in Rust.

Quick Overview

Mypy is an optional static type checker for Python. It combines the benefits of dynamic typing and static typing by adding type hints to Python code, allowing developers to catch errors early in the development process. Mypy aims to make Python more scalable, maintainable, and reliable, especially for large codebases.

Pros

  • Catches type-related errors before runtime, improving code quality and reducing bugs
  • Enhances code readability and self-documentation through type annotations
  • Provides better IDE support for autocompletion and refactoring
  • Gradual typing allows for incremental adoption in existing projects

Cons

  • Adds extra development overhead, especially when first introducing type annotations
  • May have false positives or miss some type-related issues in complex scenarios
  • Requires additional setup and integration into the development workflow
  • Some Python libraries may lack type stubs, limiting the effectiveness of type checking

Code Examples

  1. Basic type annotations:
def greet(name: str) -> str:
    return f"Hello, {name}!"

result: str = greet("Alice")
print(result)
  1. Using generic types:
from typing import List, Dict

def process_data(items: List[int]) -> Dict[str, int]:
    return {
        "sum": sum(items),
        "length": len(items)
    }

data: List[int] = [1, 2, 3, 4, 5]
result: Dict[str, int] = process_data(data)
print(result)
  1. Type checking with custom classes:
class Person:
    def __init__(self, name: str, age: int) -> None:
        self.name = name
        self.age = age

def is_adult(person: Person) -> bool:
    return person.age >= 18

alice: Person = Person("Alice", 25)
print(is_adult(alice))

Getting Started

To start using Mypy:

  1. Install Mypy:

    pip install mypy
    
  2. Add type annotations to your Python code.

  3. Run Mypy on your project:

    mypy your_file.py
    
  4. Address any type errors reported by Mypy.

  5. Optionally, integrate Mypy into your development workflow (e.g., pre-commit hooks, CI/CD pipeline).

Competitor Comparisons

13,105

Static Type Checker for Python

Pros of Pyright

  • Faster performance, especially for large codebases
  • Built-in Language Server Protocol (LSP) support
  • More comprehensive type inference in some cases

Cons of Pyright

  • Less mature and established compared to Mypy
  • Smaller community and ecosystem
  • Some advanced features require configuration

Code Comparison

Mypy:

from typing import List

def greet(names: List[str]) -> None:
    for name in names:
        print(f"Hello, {name}!")

Pyright:

def greet(names: list[str]) -> None:
    for name in names:
        print(f"Hello, {name}!")

The main difference in this example is the use of List from the typing module in Mypy, while Pyright supports using the built-in list type directly for type annotations.

Both tools provide similar functionality for type checking Python code, but they have different strengths and trade-offs. Mypy has been around longer and has broader adoption, while Pyright offers performance benefits and tighter integration with some development environments. The choice between them often depends on specific project requirements and personal preferences.

5,236

It's not just a linter that annoys you!

Pros of Pylint

  • More comprehensive linting capabilities, covering style, error detection, and coding standards
  • Highly configurable with numerous options to customize checks and reporting
  • Integrates well with various IDEs and text editors

Cons of Pylint

  • Can be slower than Mypy, especially on larger codebases
  • May produce more false positives, requiring fine-tuning of configuration
  • Learning curve can be steeper due to extensive configuration options

Code Comparison

Pylint example:

import math

def calculate_area(radius):
    return math.pi * radius ** 2

Mypy example:

import math

def calculate_area(radius: float) -> float:
    return math.pi * radius ** 2

The main difference in these examples is that Mypy focuses on type annotations, while Pylint would check for various style and potential error issues beyond just types.

Pylint is a more comprehensive linting tool that covers a wide range of code quality checks, including style, potential errors, and coding standards. It offers extensive configuration options but may require more setup time.

Mypy, on the other hand, is primarily a static type checker for Python, focusing on type annotations and type-related issues. It's generally faster and more straightforward to use for type checking but doesn't cover the broader range of linting checks that Pylint does.

Performant type-checking for python.

Pros of Pyre-check

  • Faster performance, especially for large codebases
  • Better support for incremental type checking
  • More advanced features like taint analysis and security checks

Cons of Pyre-check

  • Smaller community and ecosystem compared to Mypy
  • Less comprehensive documentation and learning resources
  • May have compatibility issues with some third-party libraries

Code Comparison

Mypy:

from typing import List

def greet(names: List[str]) -> None:
    for name in names:
        print(f"Hello, {name}!")

Pyre-check:

from typing import List

def greet(names: List[str]) -> None:
    for name in names:
        print(f"Hello, {name}!")

The code for basic type checking is identical for both tools. However, Pyre-check offers additional features for more complex scenarios, such as taint analysis:

from pyre_extensions import taint_model

@taint_model
def process_user_input(input: str) -> str:
    return input.strip()

This example demonstrates Pyre-check's taint analysis capabilities, which are not available in Mypy. Overall, while both tools serve similar purposes, Pyre-check offers some advanced features and performance benefits, particularly for larger projects, at the cost of a smaller ecosystem and potentially more challenging setup process.

4,706

A static type analyzer for Python code

Pros of pytype

  • Performs more advanced type inference, including for unannotated code
  • Supports gradual typing, allowing for incremental adoption
  • Offers better handling of dynamic Python features like metaclasses

Cons of pytype

  • Slower performance compared to mypy, especially on larger codebases
  • Less widespread adoption and community support
  • More complex setup and configuration process

Code Comparison

mypy:

def greet(name: str) -> str:
    return f"Hello, {name}!"

print(greet("World"))

pytype:

def greet(name):
    return f"Hello, {name}!"

print(greet("World"))

In this example, mypy requires explicit type annotations, while pytype can infer types without annotations. However, pytype's inference may not always be as precise as explicit annotations.

Both tools aim to improve code quality and catch type-related errors, but they differ in their approaches and trade-offs. mypy is generally faster and more widely adopted, while pytype offers more advanced type inference capabilities. The choice between them often depends on specific project requirements and team preferences.

3,391

flake8 is a python tool that glues together pycodestyle, pyflakes, mccabe, and third-party plugins to check the style and quality of some python code.

Pros of flake8

  • Faster execution time for code analysis
  • Broader scope of linting, covering style and some logical errors
  • Easier to set up and integrate into existing projects

Cons of flake8

  • Less comprehensive type checking capabilities
  • Limited ability to catch complex logical errors
  • Fewer customization options for advanced users

Code Comparison

mypy:

def greet(name: str) -> str:
    return f"Hello, {name}!"

result: str = greet(42)  # Type error

flake8:

def greet(name):
    return f"Hello, {name}!"

result = greet(42)  # No error detected

mypy would catch the type mismatch in the function call, while flake8 would not detect this issue. However, flake8 might flag other style-related issues not shown in this example.

Both tools serve different purposes and can be used complementarily. mypy focuses on static type checking, while flake8 is primarily a style guide enforcement and basic error detection tool. Many developers use both in their Python projects to ensure code quality and catch different types of issues.

30,822

An extremely fast Python linter and code formatter, written in Rust.

Pros of Ruff

  • Significantly faster performance due to being written in Rust
  • Combines linting, formatting, and some type checking in a single tool
  • Actively developed with frequent updates and new features

Cons of Ruff

  • Less comprehensive type checking compared to Mypy
  • Newer project with potentially less stability and community support
  • May not cover all edge cases that Mypy handles for static type checking

Code Comparison

Mypy:

def greet(name: str) -> str:
    return f"Hello, {name}!"

result: str = greet("Alice")

Ruff:

def greet(name: str) -> str:
    return f"Hello, {name}!"

result = greet("Alice")

While both tools can work with type annotations, Mypy focuses on comprehensive static type checking, whereas Ruff combines linting, formatting, and basic type checking. Ruff may not require explicit type annotations in all cases where Mypy would, as shown in the result variable declaration.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

mypy logo

Mypy: Static Typing for Python

Stable Version Downloads Build Status Documentation Status Chat at https://gitter.im/python/typing Checked with mypy Code style: black Linting: Ruff

Got a question?

We are always happy to answer questions! Here are some good places to ask them:

If you're just getting started, the documentation and type hints cheat sheet can also help answer questions.

If you think you've found a bug:

To report a bug or request an enhancement:

To discuss a new type system feature:

What is mypy?

Mypy is a static type checker for Python.

Type checkers help ensure that you're using variables and functions in your code correctly. With mypy, add type hints (PEP 484) to your Python programs, and mypy will warn you when you use those types incorrectly.

Python is a dynamic language, so usually you'll only see errors in your code when you attempt to run it. Mypy is a static checker, so it finds bugs in your programs without even running them!

Here is a small example to whet your appetite:

number = input("What is your favourite number?")
print("It is", number + 1)  # error: Unsupported operand types for + ("str" and "int")

Adding type hints for mypy does not interfere with the way your program would otherwise run. Think of type hints as similar to comments! You can always use the Python interpreter to run your code, even if mypy reports errors.

Mypy is designed with gradual typing in mind. This means you can add type hints to your code base slowly and that you can always fall back to dynamic typing when static typing is not convenient.

Mypy has a powerful and easy-to-use type system, supporting features such as type inference, generics, callable types, tuple types, union types, structural subtyping and more. Using mypy will make your programs easier to understand, debug, and maintain.

See the documentation for more examples and information.

In particular, see:

Quick start

Mypy can be installed using pip:

python3 -m pip install -U mypy

If you want to run the latest version of the code, you can install from the repo directly:

python3 -m pip install -U git+https://github.com/python/mypy.git
# or if you don't have 'git' installed
python3 -m pip install -U https://github.com/python/mypy/zipball/master

Now you can type-check the statically typed parts of a program like this:

mypy PROGRAM

You can always use the Python interpreter to run your statically typed programs, even if mypy reports type errors:

python3 PROGRAM

You can also try mypy in an online playground (developed by Yusuke Miyazaki). If you are working with large code bases, you can run mypy in daemon mode, that will give much faster (often sub-second) incremental updates:

dmypy run -- PROGRAM

Integrations

Mypy can be integrated into popular IDEs:

Web site and documentation

Additional information is available at the web site:

https://www.mypy-lang.org/

Jump straight to the documentation:

https://mypy.readthedocs.io/

Follow along our changelog at:

https://mypy-lang.blogspot.com/

Contributing

Help in testing, development, documentation and other tasks is highly appreciated and useful to the project. There are tasks for contributors of all experience levels.

To get started with developing mypy, see CONTRIBUTING.md.

If you need help getting started, don't hesitate to ask on gitter.

Mypyc and compiled version of mypy

Mypyc uses Python type hints to compile Python modules to faster C extensions. Mypy is itself compiled using mypyc: this makes mypy approximately 4 times faster than if interpreted!

To install an interpreted mypy instead, use:

python3 -m pip install --no-binary mypy -U mypy

To use a compiled version of a development version of mypy, directly install a binary from https://github.com/mypyc/mypy_mypyc-wheels/releases/latest.

To contribute to the mypyc project, check out https://github.com/mypyc/mypyc