Skip to main content

A flake8 plugin that flags imports exclusively used for type annotations

Project description

Package version Code coverage Test status Supported Python versions Checked with mypy

flake8-typing-only-imports

Plugin is still a work in progress

flake8 plugin that helps identify which imports to put into type-checking blocks, and how to adjust your type annotations once imports are moved.

Installation

pip install flake8-typing-only-imports

Codes

Code Description
TYO100 Import should be moved to a type-checking block
TYO101 Third-party import should be moved to a type-checking block
TYO200 Missing 'from __future__ import annotations' import
TYO201 Annotation is wrapped in unnecessary quotes
TYO300 Annotation should be wrapped in quotes
TYO301 Annotation is wrapped in unnecessary quotes

TYO101 is disabled by default because third-party imports usually aren't a real concern with respect to import circularity issues.

TYO2XX and TYO3XX are mutually exclusive as they represent two different ways of solving the same problem. Make sure to ignore or enable just one of the series.

Motivation

Two common issues when annotating large code bases are:

  1. Import circularity issues
  2. Annotating not-yet-defined structures

These problems are largely solved by two features:

  1. Type checking blocks

    from typing import TYPE_CHECKING
    
    if TYPE_CHECKING:
        # this code is not evaluated at runtime
        from foo import bar
    
  2. Forward references

    Which can be used, like this

    class Foo:
        def bar(self) -> 'Foo':
            return Foo()
    

    or since PEP563 was implemented, like this:

    from __future__ import annotations
    
    class Foo:
        def bar(self) -> Foo:
            return Foo()
    

    See this excellent stackoverflow response explaining forward references, for more context.

The aim of this plugin is to automate the management of type annotation imports, and the forward references that then become necessary.

As a pre-commit hook

See pre-commit for instructions

Sample .pre-commit-config.yaml:

- repo: https://gitlab.com/pycqa/flake8
  rev: 3.7.8
  hooks:
  - id: flake8
    additional_dependencies: [flake8-typing-only-imports]

Supporting the project

Leave a ⭐️  if this project helped you!

Contributions are always welcome 👏

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

flake8-typing-only-imports-0.1.11.tar.gz (10.0 kB view hashes)

Uploaded Source

Built Distribution

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page