JelleZijlstra / autotyping

Automatically add simple type annotations to your code
240 stars 20 forks source link
mypy python typing

When I refactor code I often find myself tediously adding type annotations that are obvious from context: functions that don't return anything, boolean flags, etcetera. That's where autotyping comes in: it automatically adds those types and inserts the right annotations.

Usage

Autotyping can be called directly from the CLI, be used as a pre-commit hook or run via the libcst interface as a codemod. Here's how to use it from the CLI:

By default it does nothing; you have to add flags to make it do more transformations. The following are supported:

There are two shortcut flags to enable multiple transformations at once:

LibCST

Autotyping is built as a LibCST codemod; see the LibCST documentation for more information on how to use codemods.

If you wish to run things through the libcst.tool interface, you can do this like so:

pre-commit hook

Pre-commit hooks are scripts that runs automatically before a commit is made, which makes them really handy for checking and enforcing code-formatting (or in this case, typing)

  1. To add autotyping as a pre-commit hook, you will first need to install pre-commit if you haven't already:

    pip install pre-commit
  2. After that, create or update the .pre-commit-config.yaml file at the root of your repository and add in:

- repos:
  - repo: https://github.com/JelleZijlstra/autotyping
    rev: 24.9.0
    hooks:
      - id: autotyping
        stages: [commit]
        types: [python]
        args: [--safe] # or alternatively, --aggressive, or any of the other flags mentioned above 
  1. Finally, run the following command to install the pre-commit hook in your repository:
pre-commit install

Now whenever you commit changes, autotyping will automatically add type annotations to your code!

Limitations

Autotyping is intended to be a simple tool that uses heuristics to find annotations that would be tedious to add by hand. The heuristics may fail, and after you run autotyping you should run a type checker to verify that the types it added are correct.

Known limitations:

Changelog

24.9.0 (September 23, 2024)

24.3.0 (March 25, 2024)

23.3.0 (March 3, 2023)

23.2.0 (February 3, 2023)

22.9.0 (September 5, 2022)

21.12.0 (December 21, 2021)