flake8-type-checking


Nameflake8-type-checking JSON
Version 2.8.0 PyPI version JSON
download
home_pagehttps://github.com/snok
SummaryA flake8 plugin for managing type-checking imports & forward references
upload_time2023-12-07 12:23:17
maintainer
docs_urlNone
authorSondre Lillebø Gundersen
requires_python>=3.8
licenseBSD-3-Clause
keywords flake8 plugin linting type hint typing imports
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            [![Package version](https://img.shields.io/pypi/v/flake8-type-checking.svg)](https://pypi.org/project/flake8-type-checking/)
[![Code coverage](https://codecov.io/gh/sondrelg/flake8-type-checking/branch/main/graph/badge.svg)](https://codecov.io/gh/sondrelg/flake8-type-checking)
[![Test status](https://github.com/sondrelg/flake8-type-checking/actions/workflows/testing.yml/badge.svg)](https://github.com/snok/flake8-type-checking/actions/workflows/testing.yml)
[![Supported Python versions](https://img.shields.io/badge/python-3.8%2B-blue)](https://pypi.org/project/flake8-type-checking/)
[![Checked with mypy](http://www.mypy-lang.org/static/mypy_badge.svg)](http://mypy-lang.org/)

# flake8-type-checking

Lets you know which imports to move in or out of
[type-checking](https://docs.python.org/3/library/typing.html#typing.TYPE_CHECKING) blocks.

The plugin assumes that the imports you only use for type hinting
*are not* required at runtime. When imports aren't strictly required at runtime, it means we can guard them.

Guarding imports provides 3 major benefits:

- 🔧  It reduces import circularity issues,
- 🧹  It organizes imports, and
- 🚀  It completely eliminates the overhead of type hint imports at runtime

<br>

Essentially, this code:

```python
import pandas  # 15mb library

x: pandas.DataFrame
```

becomes this:

```python
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    import pandas  # <-- no longer imported at runtime

x: "pandas.DataFrame"
```

More examples can be found in the [examples](#examples) section.

<br>

If you're using [pydantic](https://pydantic-docs.helpmanual.io/),
[fastapi](https://fastapi.tiangolo.com/), [cattrs](https://github.com/python-attrs/cattrs),
or [injector](https://github.com/python-injector/injector)
see the [configuration](#configuration) for how to enable support.

## Primary features

The plugin will:

- Tell you when an import should be moved into a type-checking block
- Tell you when an import should be moved out again

And depending on which error code range you've opted into, it will tell you

- Whether you need to add a `from __future__ import annotations` import
- Whether you need to quote an annotation
- Whether you can unquote a quoted annotation

## Error codes

| Code  | Description                                                                               |
|-------|-------------------------------------------------------------------------------------------|
| TC001 | Move application import into a type-checking block                                        |
| TC002 | Move third-party import into a type-checking block                                        |
| TC003 | Move built-in import into a type-checking block                                           |
| TC004 | Move import out of type-checking block. Import is used for more than type hinting.        |
| TC005 | Found empty type-checking block                                                           |
| TC006 | Annotation in typing.cast() should be a string literal                                    |
| TC007 | Type alias needs to be made into a string literal                                         |
| TC008 | Type alias does not need to be a string literal                                           |
| TC009 | Move declaration out of type-checking block. Variable is used for more than type hinting. |

## Choosing how to handle forward references

You need to choose whether to opt-into using the
`TC100`- or the `TC200`-range of error codes.

They represent two different ways of solving the same problem, so please only choose one.

`TC100` and `TC101` manage forward references by taking advantage of
[postponed evaluation of annotations](https://www.python.org/dev/peps/pep-0563/).

| Code  | Description                                         |
|-------|-----------------------------------------------------|
| TC100 | Add 'from \_\_future\_\_ import annotations' import |
| TC101 | Annotation does not need to be a string literal     |

`TC200` and `TC201` manage forward references using [string literals](https://www.python.org/dev/peps/pep-0484/#forward-references).

| Code  | Description                                         |
|-------|-----------------------------------------------------|
| TC200 | Annotation needs to be made into a string literal   |
| TC201 | Annotation does not need to be a string literal     |

## Enabling error ranges

Add `TC` and `TC1` or `TC2` to your flake8 config like this:

```ini
[flake8]
max-line-length = 80
max-complexity = 12
...
ignore = E501
# You can use 'extend-select' (new in flake8 v4):
extend-select = TC, TC2
# OR 'select':
select = C,E,F..., TC, TC2  # or TC1
# OR 'enable-extensions':
enable-extensions = TC, TC2  # or TC1
```

If you are unsure which `TC` range to pick, see the [rationale](#rationale) for more info.

## Installation

```shell
pip install flake8-type-checking
```

## Configuration

These options are configurable, and can be set in your flake8 config.

### Exempt modules

If you wish to exempt certain modules from
needing to be moved into type-checking blocks, you can specify which
modules to ignore.

- **setting name**: `type-checking-exempt-modules`
- **type**: `list`

```ini
[flake8]
type-checking-exempt-modules = typing_extensions  # default []
```

### Strict

The plugin, by default, will report TC00[1-3] errors
for imports if there aren't already other imports from the same module.
When there are other imports from the same module,
the import circularity and performance benefits no longer
apply from guarding an import.

When strict mode is enabled, the plugin will flag all
imports that *can* be moved.

- **setting name**: `type-checking-strict`
- **type**: `bool`

```ini
[flake8]
type-checking-strict = true  # default false
```

### Pydantic support

If you use Pydantic models in your code, you should enable Pydantic support.
This will treat any class variable annotation as being needed during runtime.

- **name**: `type-checking-pydantic-enabled`
- **type**: `bool`
```ini
[flake8]
type-checking-pydantic-enabled = true  # default false
```
### Pydantic support base-class passlist

Disabling checks for all class annotations is a little aggressive.

If you feel comfortable that all base classes named, e.g., `NamedTuple` are *not* Pydantic models,
then you can pass the names of the base classes in this setting, to re-enable checking for classes
which inherit from them.

- **name**: `type-checking-pydantic-enabled-baseclass-passlist`
- **type**: `list`
```ini
[flake8]
type-checking-pydantic-enabled-baseclass-passlist = NamedTuple, TypedDict  # default []
```

### FastAPI support

If you're using the plugin for a FastAPI project,
you should enable support. This will treat the annotations
of any decorated function as needed at runtime.

Enabling FastAPI support will also enable Pydantic support.

- **name**: `type-checking-fastapi-enabled`
- **type**: `bool`
```ini
[flake8]
type-checking-fastapi-enabled = true  # default false
```

One more thing to note for FastAPI users is that dependencies
(functions used in `Depends`) will produce false positives, unless
you enable dependency support as described below.

### FastAPI dependency support

In addition to preventing false positives for decorators, we *can*
prevent false positives for dependencies. We are making a pretty bad
trade-off however: by enabling this option we treat every annotation
in every function definition across your entire project as a possible
dependency annotation. In other words, we stop linting all function
annotations completely, to avoid the possibility of false positives.
If you prefer to be on the safe side, you should enable this - otherwise
it might be enough to be aware that false positives can happen for functions
used as dependencies.

Enabling dependency support will also enable FastAPI and Pydantic support.

- **name**: `type-checking-fastapi-dependency-support-enabled`
- **type**: `bool`
```ini
[flake8]
type-checking-fastapi-dependency-support-enabled = true  # default false
```

### SQLAlchemy 2.0+ support

If you're using SQLAlchemy 2.0+, you can enable support.
This will treat any `Mapped[...]` types as needed at runtime.
It will also specially treat the enclosed type, since it may or may not
need to be available at runtime depending on whether or not the enclosed
type is a model or not, since models can have circular dependencies.

- **name**: `type-checking-sqlalchemy-enabled`
- **type**: `bool`
```ini
type-checking-sqlalchemy-enabled = true  # default false
```

### SQLAlchemy 2.0+ support mapped dotted names

Since it's possible to create subclasses of `sqlalchemy.orm.Mapped` that
define some custom behavior for the mapped attribute, but otherwise still
behave like any other mapped attribute, i.e. the same runtime restrictions
apply it's possible to provide additional dotted names that should be treated
like subclasses of `Mapped`. By default we check for `sqlalchemy.orm.Mapped`,
`sqlalchemy.orm.DynamicMapped` and `sqlalchemy.orm.WriteOnlyMapped`.

If there's more than one import path for the same `Mapped` subclass, then you
need to specify each of them as a separate dotted name.

- **name**: `type-checking-sqlalchemy-mapped-dotted-names`
- **type**: `list`
```ini
type-checking-sqlalchemy-mapped-dotted-names = a.MyMapped, a.b.MyMapped  # default []
```

### Cattrs support

If you're using the plugin in a project which uses `cattrs`,
you can enable support. This will treat the annotations
of any decorated `attrs` class as needed at runtime, since
`cattrs.unstructure` calls will fail when loading
classes where types are not available at runtime.

Note: the cattrs support setting does not yet detect and
ignore class var annotations on dataclasses or other non-attrs class types.
This can be added in the future if needed.

- **name**: `type-checking-cattrs-enabled`
- **type**: `bool`
```ini
[flake8]
type-checking-cattrs-enabled = true  # default false
```

### Injector support

If you're using the injector library, you can enable support.
This will treat any `Inject[Dependency]` types as needed at runtime.

- **name**: `type-checking-injector-enabled`
- **type**: `bool`
```ini
type-checking-injector-enabled = true  # default false
```

## Rationale

Why did we create this plugin?

Good type hinting typically requires a lot of project imports, which can increase
the risk of [import cycles](https://mypy.readthedocs.io/en/stable/runtime_troubles.html?#import-cycles)
in a project. The recommended way of preventing this problem is to use `typing.TYPE_CHECKING` blocks
to guard these types of imports. In particular, `TC001` helps protect against this issue.

Once imports are guarded, they will no longer be evaluated/imported during runtime. The
consequence of this is that these imports can no longer be treated as if they
were imported outside the block. Instead we need to use [forward references](https://www.python.org/dev/peps/pep-0484/#forward-references).

For Python version `>= 3.7`, there are actually two ways of solving this issue.
You can either make your annotations string literals, or you can use a `__futures__` import to enable [postponed evaluation of annotations](https://www.python.org/dev/peps/pep-0563/).
See [this](https://stackoverflow.com/a/55344418/8083459) excellent stackoverflow answer
for a great explanation of the differences.

## Examples

<details>
<summary><b>Performance example</b></summary>

Imports for type hinting can have a performance impact.

```python
import pandas


def dataframe_length(df: pandas.DataFrame) -> int:
    return len(df)
```

In this example, we import a 15mb library, for a single type hint.

We don't need to perform this operation at runtime, *at all*.
If we know that the import will not otherwise be needed by surrounding code,
we can simply guard it, like this:

```python
from typing import TYPE_CHECKING


if TYPE_CHECKING:
    import pandas  # <-- no longer imported at runtime


def dataframe_length(df: "pandas.DataFrame") -> int:
    return len(df)
```

Now the import is no longer made at runtime. If you're unsure about how this works, see the [mypy docs](https://mypy.readthedocs.io/en/stable/runtime_troubles.html?#typing-type-checking) for a basic introduction.
</details>

<details>
<summary><b>Import circularity example</b></summary>

**Bad code**

`models/a.py`
```python
from models.b import B

class A(Model):
    def foo(self, b: B): ...
```

`models/b.py`
```python
from models.a import A

class B(Model):
    def bar(self, a: A): ...
```

Will result in these errors

```shell
>> a.py: TC002 Move third-party import 'models.b.B' into a type-checking block
>> b.py: TC002 Move third-party import 'models.a.A' into a type-checking block
```

and consequently trigger these errors if imports are purely moved into type-checking block, without proper forward reference handling

```shell
>> a.py: TC100 Add 'from __future__ import annotations' import
>> b.py: TC100 Add 'from __future__ import annotations' import
```

or

```shell
>> a.py: TC200 Annotation 'B' needs to be made into a string literal
>> b.py: TC200 Annotation 'A' needs to be made into a string literal
```

**Good code**

`models/a.py`
```python
# TC1
from __future__ import annotations

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from models.b import B

class A(Model):
    def foo(self, b: B): ...
```
or
```python
# TC2
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from models.b import B

class A(Model):
    def foo(self, b: 'B'): ...
```

`models/b.py`
```python
# TC1
from __future__ import annotations

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from models.a import A

class B(Model):
    def bar(self, a: A): ...
```

or

```python
# TC2
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from models.a import A

class B(Model):
    def bar(self, a: 'A'): ...
```
</details>

<details>
<summary><b>Examples from the wild</b></summary>

Here are a few examples of public projects that use `flake8-type-checking`:

- [Example from the Poetry codebase](https://github.com/python-poetry/poetry/blob/714c09dd845c58079cff3f3cbedc114dff2194c9/src/poetry/factory.py#L1:L33)
- [Example from the asgi-correlation-id codebase](https://github.com/snok/asgi-correlation-id/blob/main/asgi_correlation_id/middleware.py#L1:L12)

</details>

## Running the plugin as a pre-commit hook

You can run this flake8 plugin as a [pre-commit](https://github.com/pre-commit/pre-commit) hook:

```yaml
- repo: https://github.com/pycqa/flake8
  rev: 4.0.1
  hooks:
    - id: flake8
      additional_dependencies:
        - flake8-type-checking
```

## Contributing

Please feel free to open an issue or a PR 👏

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/snok",
    "name": "flake8-type-checking",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": "",
    "keywords": "flake8,plugin,linting,type hint,typing,imports",
    "author": "Sondre Lilleb\u00f8 Gundersen",
    "author_email": "sondrelg@live.no",
    "download_url": "https://files.pythonhosted.org/packages/a2/48/ccf2ff874c2b5aaaf1cb32c3832bbd598bc49df45dbacf2810a06d37be61/flake8_type_checking-2.8.0.tar.gz",
    "platform": null,
    "description": "[![Package version](https://img.shields.io/pypi/v/flake8-type-checking.svg)](https://pypi.org/project/flake8-type-checking/)\n[![Code coverage](https://codecov.io/gh/sondrelg/flake8-type-checking/branch/main/graph/badge.svg)](https://codecov.io/gh/sondrelg/flake8-type-checking)\n[![Test status](https://github.com/sondrelg/flake8-type-checking/actions/workflows/testing.yml/badge.svg)](https://github.com/snok/flake8-type-checking/actions/workflows/testing.yml)\n[![Supported Python versions](https://img.shields.io/badge/python-3.8%2B-blue)](https://pypi.org/project/flake8-type-checking/)\n[![Checked with mypy](http://www.mypy-lang.org/static/mypy_badge.svg)](http://mypy-lang.org/)\n\n# flake8-type-checking\n\nLets you know which imports to move in or out of\n[type-checking](https://docs.python.org/3/library/typing.html#typing.TYPE_CHECKING) blocks.\n\nThe plugin assumes that the imports you only use for type hinting\n*are not* required at runtime. When imports aren't strictly required at runtime, it means we can guard them.\n\nGuarding imports provides 3 major benefits:\n\n- \ud83d\udd27&nbsp;&nbsp;It reduces import circularity issues,\n- \ud83e\uddf9&nbsp;&nbsp;It organizes imports, and\n- \ud83d\ude80&nbsp;&nbsp;It completely eliminates the overhead of type hint imports at runtime\n\n<br>\n\nEssentially, this code:\n\n```python\nimport pandas  # 15mb library\n\nx: pandas.DataFrame\n```\n\nbecomes this:\n\n```python\nfrom typing import TYPE_CHECKING\n\nif TYPE_CHECKING:\n    import pandas  # <-- no longer imported at runtime\n\nx: \"pandas.DataFrame\"\n```\n\nMore examples can be found in the [examples](#examples) section.\n\n<br>\n\nIf you're using [pydantic](https://pydantic-docs.helpmanual.io/),\n[fastapi](https://fastapi.tiangolo.com/), [cattrs](https://github.com/python-attrs/cattrs),\nor [injector](https://github.com/python-injector/injector)\nsee the [configuration](#configuration) for how to enable support.\n\n## Primary features\n\nThe plugin will:\n\n- Tell you when an import should be moved into a type-checking block\n- Tell you when an import should be moved out again\n\nAnd depending on which error code range you've opted into, it will tell you\n\n- Whether you need to add a `from __future__ import annotations` import\n- Whether you need to quote an annotation\n- Whether you can unquote a quoted annotation\n\n## Error codes\n\n| Code  | Description                                                                               |\n|-------|-------------------------------------------------------------------------------------------|\n| TC001 | Move application import into a type-checking block                                        |\n| TC002 | Move third-party import into a type-checking block                                        |\n| TC003 | Move built-in import into a type-checking block                                           |\n| TC004 | Move import out of type-checking block. Import is used for more than type hinting.        |\n| TC005 | Found empty type-checking block                                                           |\n| TC006 | Annotation in typing.cast() should be a string literal                                    |\n| TC007 | Type alias needs to be made into a string literal                                         |\n| TC008 | Type alias does not need to be a string literal                                           |\n| TC009 | Move declaration out of type-checking block. Variable is used for more than type hinting. |\n\n## Choosing how to handle forward references\n\nYou need to choose whether to opt-into using the\n`TC100`- or the `TC200`-range of error codes.\n\nThey represent two different ways of solving the same problem, so please only choose one.\n\n`TC100` and `TC101` manage forward references by taking advantage of\n[postponed evaluation of annotations](https://www.python.org/dev/peps/pep-0563/).\n\n| Code  | Description                                         |\n|-------|-----------------------------------------------------|\n| TC100 | Add 'from \\_\\_future\\_\\_ import annotations' import |\n| TC101 | Annotation does not need to be a string literal     |\n\n`TC200` and `TC201` manage forward references using [string literals](https://www.python.org/dev/peps/pep-0484/#forward-references).\n\n| Code  | Description                                         |\n|-------|-----------------------------------------------------|\n| TC200 | Annotation needs to be made into a string literal   |\n| TC201 | Annotation does not need to be a string literal     |\n\n## Enabling error ranges\n\nAdd `TC` and `TC1` or `TC2` to your flake8 config like this:\n\n```ini\n[flake8]\nmax-line-length = 80\nmax-complexity = 12\n...\nignore = E501\n# You can use 'extend-select' (new in flake8 v4):\nextend-select = TC, TC2\n# OR 'select':\nselect = C,E,F..., TC, TC2  # or TC1\n# OR 'enable-extensions':\nenable-extensions = TC, TC2  # or TC1\n```\n\nIf you are unsure which `TC` range to pick, see the [rationale](#rationale) for more info.\n\n## Installation\n\n```shell\npip install flake8-type-checking\n```\n\n## Configuration\n\nThese options are configurable, and can be set in your flake8 config.\n\n### Exempt modules\n\nIf you wish to exempt certain modules from\nneeding to be moved into type-checking blocks, you can specify which\nmodules to ignore.\n\n- **setting name**: `type-checking-exempt-modules`\n- **type**: `list`\n\n```ini\n[flake8]\ntype-checking-exempt-modules = typing_extensions  # default []\n```\n\n### Strict\n\nThe plugin, by default, will report TC00[1-3] errors\nfor imports if there aren't already other imports from the same module.\nWhen there are other imports from the same module,\nthe import circularity and performance benefits no longer\napply from guarding an import.\n\nWhen strict mode is enabled, the plugin will flag all\nimports that *can* be moved.\n\n- **setting name**: `type-checking-strict`\n- **type**: `bool`\n\n```ini\n[flake8]\ntype-checking-strict = true  # default false\n```\n\n### Pydantic support\n\nIf you use Pydantic models in your code, you should enable Pydantic support.\nThis will treat any class variable annotation as being needed during runtime.\n\n- **name**: `type-checking-pydantic-enabled`\n- **type**: `bool`\n```ini\n[flake8]\ntype-checking-pydantic-enabled = true  # default false\n```\n### Pydantic support base-class passlist\n\nDisabling checks for all class annotations is a little aggressive.\n\nIf you feel comfortable that all base classes named, e.g., `NamedTuple` are *not* Pydantic models,\nthen you can pass the names of the base classes in this setting, to re-enable checking for classes\nwhich inherit from them.\n\n- **name**: `type-checking-pydantic-enabled-baseclass-passlist`\n- **type**: `list`\n```ini\n[flake8]\ntype-checking-pydantic-enabled-baseclass-passlist = NamedTuple, TypedDict  # default []\n```\n\n### FastAPI support\n\nIf you're using the plugin for a FastAPI project,\nyou should enable support. This will treat the annotations\nof any decorated function as needed at runtime.\n\nEnabling FastAPI support will also enable Pydantic support.\n\n- **name**: `type-checking-fastapi-enabled`\n- **type**: `bool`\n```ini\n[flake8]\ntype-checking-fastapi-enabled = true  # default false\n```\n\nOne more thing to note for FastAPI users is that dependencies\n(functions used in `Depends`) will produce false positives, unless\nyou enable dependency support as described below.\n\n### FastAPI dependency support\n\nIn addition to preventing false positives for decorators, we *can*\nprevent false positives for dependencies. We are making a pretty bad\ntrade-off however: by enabling this option we treat every annotation\nin every function definition across your entire project as a possible\ndependency annotation. In other words, we stop linting all function\nannotations completely, to avoid the possibility of false positives.\nIf you prefer to be on the safe side, you should enable this - otherwise\nit might be enough to be aware that false positives can happen for functions\nused as dependencies.\n\nEnabling dependency support will also enable FastAPI and Pydantic support.\n\n- **name**: `type-checking-fastapi-dependency-support-enabled`\n- **type**: `bool`\n```ini\n[flake8]\ntype-checking-fastapi-dependency-support-enabled = true  # default false\n```\n\n### SQLAlchemy 2.0+ support\n\nIf you're using SQLAlchemy 2.0+, you can enable support.\nThis will treat any `Mapped[...]` types as needed at runtime.\nIt will also specially treat the enclosed type, since it may or may not\nneed to be available at runtime depending on whether or not the enclosed\ntype is a model or not, since models can have circular dependencies.\n\n- **name**: `type-checking-sqlalchemy-enabled`\n- **type**: `bool`\n```ini\ntype-checking-sqlalchemy-enabled = true  # default false\n```\n\n### SQLAlchemy 2.0+ support mapped dotted names\n\nSince it's possible to create subclasses of `sqlalchemy.orm.Mapped` that\ndefine some custom behavior for the mapped attribute, but otherwise still\nbehave like any other mapped attribute, i.e. the same runtime restrictions\napply it's possible to provide additional dotted names that should be treated\nlike subclasses of `Mapped`. By default we check for `sqlalchemy.orm.Mapped`,\n`sqlalchemy.orm.DynamicMapped` and `sqlalchemy.orm.WriteOnlyMapped`.\n\nIf there's more than one import path for the same `Mapped` subclass, then you\nneed to specify each of them as a separate dotted name.\n\n- **name**: `type-checking-sqlalchemy-mapped-dotted-names`\n- **type**: `list`\n```ini\ntype-checking-sqlalchemy-mapped-dotted-names = a.MyMapped, a.b.MyMapped  # default []\n```\n\n### Cattrs support\n\nIf you're using the plugin in a project which uses `cattrs`,\nyou can enable support. This will treat the annotations\nof any decorated `attrs` class as needed at runtime, since\n`cattrs.unstructure` calls will fail when loading\nclasses where types are not available at runtime.\n\nNote: the cattrs support setting does not yet detect and\nignore class var annotations on dataclasses or other non-attrs class types.\nThis can be added in the future if needed.\n\n- **name**: `type-checking-cattrs-enabled`\n- **type**: `bool`\n```ini\n[flake8]\ntype-checking-cattrs-enabled = true  # default false\n```\n\n### Injector support\n\nIf you're using the injector library, you can enable support.\nThis will treat any `Inject[Dependency]` types as needed at runtime.\n\n- **name**: `type-checking-injector-enabled`\n- **type**: `bool`\n```ini\ntype-checking-injector-enabled = true  # default false\n```\n\n## Rationale\n\nWhy did we create this plugin?\n\nGood type hinting typically requires a lot of project imports, which can increase\nthe risk of [import cycles](https://mypy.readthedocs.io/en/stable/runtime_troubles.html?#import-cycles)\nin a project. The recommended way of preventing this problem is to use `typing.TYPE_CHECKING` blocks\nto guard these types of imports. In particular, `TC001` helps protect against this issue.\n\nOnce imports are guarded, they will no longer be evaluated/imported during runtime. The\nconsequence of this is that these imports can no longer be treated as if they\nwere imported outside the block. Instead we need to use [forward references](https://www.python.org/dev/peps/pep-0484/#forward-references).\n\nFor Python version `>= 3.7`, there are actually two ways of solving this issue.\nYou can either make your annotations string literals, or you can use a `__futures__` import to enable [postponed evaluation of annotations](https://www.python.org/dev/peps/pep-0563/).\nSee [this](https://stackoverflow.com/a/55344418/8083459) excellent stackoverflow answer\nfor a great explanation of the differences.\n\n## Examples\n\n<details>\n<summary><b>Performance example</b></summary>\n\nImports for type hinting can have a performance impact.\n\n```python\nimport pandas\n\n\ndef dataframe_length(df: pandas.DataFrame) -> int:\n    return len(df)\n```\n\nIn this example, we import a 15mb library, for a single type hint.\n\nWe don't need to perform this operation at runtime, *at all*.\nIf we know that the import will not otherwise be needed by surrounding code,\nwe can simply guard it, like this:\n\n```python\nfrom typing import TYPE_CHECKING\n\n\nif TYPE_CHECKING:\n    import pandas  # <-- no longer imported at runtime\n\n\ndef dataframe_length(df: \"pandas.DataFrame\") -> int:\n    return len(df)\n```\n\nNow the import is no longer made at runtime. If you're unsure about how this works, see the [mypy docs](https://mypy.readthedocs.io/en/stable/runtime_troubles.html?#typing-type-checking) for a basic introduction.\n</details>\n\n<details>\n<summary><b>Import circularity example</b></summary>\n\n**Bad code**\n\n`models/a.py`\n```python\nfrom models.b import B\n\nclass A(Model):\n    def foo(self, b: B): ...\n```\n\n`models/b.py`\n```python\nfrom models.a import A\n\nclass B(Model):\n    def bar(self, a: A): ...\n```\n\nWill result in these errors\n\n```shell\n>> a.py: TC002 Move third-party import 'models.b.B' into a type-checking block\n>> b.py: TC002 Move third-party import 'models.a.A' into a type-checking block\n```\n\nand consequently trigger these errors if imports are purely moved into type-checking block, without proper forward reference handling\n\n```shell\n>> a.py: TC100 Add 'from __future__ import annotations' import\n>> b.py: TC100 Add 'from __future__ import annotations' import\n```\n\nor\n\n```shell\n>> a.py: TC200 Annotation 'B' needs to be made into a string literal\n>> b.py: TC200 Annotation 'A' needs to be made into a string literal\n```\n\n**Good code**\n\n`models/a.py`\n```python\n# TC1\nfrom __future__ import annotations\n\nfrom typing import TYPE_CHECKING\n\nif TYPE_CHECKING:\n    from models.b import B\n\nclass A(Model):\n    def foo(self, b: B): ...\n```\nor\n```python\n# TC2\nfrom typing import TYPE_CHECKING\n\nif TYPE_CHECKING:\n    from models.b import B\n\nclass A(Model):\n    def foo(self, b: 'B'): ...\n```\n\n`models/b.py`\n```python\n# TC1\nfrom __future__ import annotations\n\nfrom typing import TYPE_CHECKING\n\nif TYPE_CHECKING:\n    from models.a import A\n\nclass B(Model):\n    def bar(self, a: A): ...\n```\n\nor\n\n```python\n# TC2\nfrom typing import TYPE_CHECKING\n\nif TYPE_CHECKING:\n    from models.a import A\n\nclass B(Model):\n    def bar(self, a: 'A'): ...\n```\n</details>\n\n<details>\n<summary><b>Examples from the wild</b></summary>\n\nHere are a few examples of public projects that use `flake8-type-checking`:\n\n- [Example from the Poetry codebase](https://github.com/python-poetry/poetry/blob/714c09dd845c58079cff3f3cbedc114dff2194c9/src/poetry/factory.py#L1:L33)\n- [Example from the asgi-correlation-id codebase](https://github.com/snok/asgi-correlation-id/blob/main/asgi_correlation_id/middleware.py#L1:L12)\n\n</details>\n\n## Running the plugin as a pre-commit hook\n\nYou can run this flake8 plugin as a [pre-commit](https://github.com/pre-commit/pre-commit) hook:\n\n```yaml\n- repo: https://github.com/pycqa/flake8\n  rev: 4.0.1\n  hooks:\n    - id: flake8\n      additional_dependencies:\n        - flake8-type-checking\n```\n\n## Contributing\n\nPlease feel free to open an issue or a PR \ud83d\udc4f\n",
    "bugtrack_url": null,
    "license": "BSD-3-Clause",
    "summary": "A flake8 plugin for managing type-checking imports & forward references",
    "version": "2.8.0",
    "project_urls": {
        "Homepage": "https://github.com/snok",
        "Releases": "https://github.com/snok/flake8-type-checking/releases",
        "Repository": "https://github.com/snok/flake8-type-checking"
    },
    "split_keywords": [
        "flake8",
        "plugin",
        "linting",
        "type hint",
        "typing",
        "imports"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "965dbc3e6c847f00bd7945cfc942e2d929d7e1c82ce2caf2678c2013526ebb04",
                "md5": "427c60e439d092919273b225f94c9096",
                "sha256": "a6f9ded325f0c9845f073609c557bf481882adc4d18571a39b137ef2d284dc85"
            },
            "downloads": -1,
            "filename": "flake8_type_checking-2.8.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "427c60e439d092919273b225f94c9096",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 29614,
            "upload_time": "2023-12-07T12:23:16",
            "upload_time_iso_8601": "2023-12-07T12:23:16.472124Z",
            "url": "https://files.pythonhosted.org/packages/96/5d/bc3e6c847f00bd7945cfc942e2d929d7e1c82ce2caf2678c2013526ebb04/flake8_type_checking-2.8.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "a248ccf2ff874c2b5aaaf1cb32c3832bbd598bc49df45dbacf2810a06d37be61",
                "md5": "45b4057266255aaa6b971c158951b662",
                "sha256": "07d949b686f39eb0cb828a394aa29d48bd1ca0df92d552d9794d17b22c309cd7"
            },
            "downloads": -1,
            "filename": "flake8_type_checking-2.8.0.tar.gz",
            "has_sig": false,
            "md5_digest": "45b4057266255aaa6b971c158951b662",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 31512,
            "upload_time": "2023-12-07T12:23:17",
            "upload_time_iso_8601": "2023-12-07T12:23:17.996737Z",
            "url": "https://files.pythonhosted.org/packages/a2/48/ccf2ff874c2b5aaaf1cb32c3832bbd598bc49df45dbacf2810a06d37be61/flake8_type_checking-2.8.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-12-07 12:23:17",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "snok",
    "github_project": "flake8-type-checking",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "flake8-type-checking"
}
        
Elapsed time: 0.20911s