flake8-import-guard


Nameflake8-import-guard JSON
Version 1.0.0 PyPI version JSON
download
home_pagehttps://qiita.com/inetcpl
SummaryFlake8 plugin to enforce import restrictions in Python projects.
upload_time2024-08-12 13:58:14
maintainerNone
docs_urlNone
authorK'
requires_python<4.0.0,>=3.8.1
licenseMIT
keywords flake8 plugin import linter
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            
![GitHub License](https://img.shields.io/github/license/K-dash/flake8-import-guard)
[![PyPI version](https://img.shields.io/pypi/v/flake8-import-guard.svg)](https://pypi.org/project/flake8-import-guard/)
[![Downloads](https://static.pepy.tech/badge/flake8-import-guard)](https://pepy.tech/project/flake8-import-guard)
![Static Badge](https://img.shields.io/badge/Flake8-%5Ev7.1.0-blue?style=flat)
[![Python versions](https://img.shields.io/pypi/pyversions/flake8-import-guard.svg)](https://pypi.org/project/flake8-import-guard/)
[![codecov](https://codecov.io/gh/K-dash/flake8-import-guard/graph/badge.svg?token=4GG16B2ZU0)](https://codecov.io/gh/K-dash/flake8-import-guard)
![GitHub last commit](https://img.shields.io/github/last-commit/K-dash/flake8-import-guard)


# Flake8 Import Guard 💂

Flake8 Import Guard is a Flake8 plugin that helps enforce import restrictions in your Python projects. It allows you to specify forbidden imports and detects their usage in your codebase, focusing on newly added imports in version-controlled files.

- [flake8-import-guard on PyPI](https://pypi.org/project/flake8-import-guard/)
- [Introductory post on reddit](https://www.reddit.com/r/Python/comments/1eoip79/flake8_import_guard_automate_import_restriction/)

## Features

- 🚫 Detects forbidden imports in new and modified files
- 🔧 Configurable via .flake8 or pyproject.toml
- 🔍 Focuses on newly added imports in Git-versioned files
- 🔗 Seamless integration with existing Flake8 workflows

## Motivation

Flake8 Import Guard is designed to address several common challenges in Python development.

- **Enforcing Security Measures**
    - Prevent the use of potentially unsafe or deprecated modules, enhancing the overall security of your codebase.
    - Prevent the import of forbidden external libraries, maintaining better control over your project's external dependencies.

- **Dependency Management**
    - Restrict and control project dependencies, reducing complexity and potential conflicts.

- **License Compliance**
    - Ensure compliance with licensing requirements by preventing the use of libraries with incompatible licenses.

- **Performance Optimization**
    - Avoid the use of heavyweight or inefficient imports that could impact performance.

- **Coding Standards Enforcement**
    - Maintain consistent coding standards across your project by enforcing specific import patterns.

- **Gradual Deprecation of Legacy Code**
    - Facilitate the phasing out of old modules or deprecated imports as your project evolves.

By using Flake8 Import Guard, development teams can proactively manage their codebase, ensuring better quality, security, and maintainability of their Python projects.

## Installation

You can install Flake8 Import Guard using pip.

```
pip install flake8-import-guard
```

## Usage

Once installed, Flake8 Import Guard will automatically be used by Flake8. You can run it using the standard Flake8 command.

```
flake8 path/to/your/code
```

## Recommended Integration

It is highly recommended to integrate Flake8 Import Guard into your pre-commit hooks and CI workflows. This ensures that import restrictions are enforced consistently across your development process, catching potential violations early and maintaining code quality standards.

## Configuration

You can configure Flake8 Import Guard using Flake8's standard configuration system or through `pyproject.toml`.

For example, let's say you want to prohibit the use of `load_dotenv` and `subprocess` in your project. Here's how you would configure that.

### Using Flake8 Configuration

Add the following to your `.flake8` file.

```ini
[flake8]
forbidden_imports = load_dotenv,subprocess
```

### Using pyproject.toml

Add the following to your `pyproject.toml` file.

```toml
[tool.flake8-import-guard]
forbidden_imports = [
    "load_dotenv",
    "subprocess"
]
```

## Example

### Configuration

Let's say you have the following configuration in your `.flake8` file.

```ini
[flake8]
forbidden_imports = load_dotenv,subprocess
```

### Sample Python File

Consider the following Python file.

```python
# test_file.py
import os
from datetime import datetime

from subprocess import check_output  # Violation Module

from dotenv import load_dotenv       # Violation Module

def main():
    pass

if __name__ == "__main__":
    main()
```

### Execution and Result

When you run Flake8 on this file, you'll get the following output.

```console
$ flake8 test_file.py
test_file.py:4:1: CPE001 Forbidden import found: subprocess.check_output
test_file.py:6:1: CPE001 Forbidden import found: dotenv.load_dotenv
```

## How It Works

`flake8-import-guard` uses Git to detect changes in your codebase and enforce import restrictions. Here's a detailed explanation of its operation.


1. For new files
   - It checks all imports against the forbidden list.
   - Any import found in the forbidden list is reported as a violation.

2. For existing files
   - It compares the current version with the last committed version to identify newly added imports.
   - Only newly added imports that match the forbidden list are reported as violations.

> [!IMPORTANT]
> If a forbidden import already exists in the file at the time of introducing `flake8-import-guard`, it will not be detected as a violation. The plugin focuses only on new changes to prevent disruption to existing codebases.

3. Violation reporting
   - Only newly added imports that match the forbidden list are reported as violations.
   - This approach allows for gradual implementation of import restrictions without causing immediate breaks in existing code.

This behavior ensures that introducing `flake8-import-guard` to an existing project doesn't immediately flag all existing forbidden imports, allowing for a smoother integration and gradual code improvement.


## Capabilities and Limitations

### What It Can Do

- Detect newly added forbidden imports in both new and existing files
- Work with Git-versioned projects
- Configure forbidden imports through Flake8 config or pyproject.toml
- Integrate seamlessly with existing Flake8 workflows

### What It Cannot Do

- Work in non-Git environments
- Identify removed or modified imports (focus is on new additions only)
- Detect indirect imports (e.g., imports within imported modules)

## Error Codes

- CPE001: Forbidden import found

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.
See [CONTRIBUTING.md](https://github.com/K-dash/flake8-import-guard/blob/main/CONTRIBUTING.md) to get an idea of how contributions work.

## License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

            

Raw data

            {
    "_id": null,
    "home_page": "https://qiita.com/inetcpl",
    "name": "flake8-import-guard",
    "maintainer": null,
    "docs_url": null,
    "requires_python": "<4.0.0,>=3.8.1",
    "maintainer_email": null,
    "keywords": "flake8, plugin, import, linter",
    "author": "K' ",
    "author_email": "51281148+K-dash@users.noreply.github.com",
    "download_url": "https://files.pythonhosted.org/packages/11/c9/b2c0627b1bb83237e9665cd25a0dc0938ba03f3f42e0c8770b714524d4d3/flake8_import_guard-1.0.0.tar.gz",
    "platform": null,
    "description": "\n![GitHub License](https://img.shields.io/github/license/K-dash/flake8-import-guard)\n[![PyPI version](https://img.shields.io/pypi/v/flake8-import-guard.svg)](https://pypi.org/project/flake8-import-guard/)\n[![Downloads](https://static.pepy.tech/badge/flake8-import-guard)](https://pepy.tech/project/flake8-import-guard)\n![Static Badge](https://img.shields.io/badge/Flake8-%5Ev7.1.0-blue?style=flat)\n[![Python versions](https://img.shields.io/pypi/pyversions/flake8-import-guard.svg)](https://pypi.org/project/flake8-import-guard/)\n[![codecov](https://codecov.io/gh/K-dash/flake8-import-guard/graph/badge.svg?token=4GG16B2ZU0)](https://codecov.io/gh/K-dash/flake8-import-guard)\n![GitHub last commit](https://img.shields.io/github/last-commit/K-dash/flake8-import-guard)\n\n\n# Flake8 Import Guard \ud83d\udc82\n\nFlake8 Import Guard is a Flake8 plugin that helps enforce import restrictions in your Python projects. It allows you to specify forbidden imports and detects their usage in your codebase, focusing on newly added imports in version-controlled files.\n\n- [flake8-import-guard on PyPI](https://pypi.org/project/flake8-import-guard/)\n- [Introductory post on reddit](https://www.reddit.com/r/Python/comments/1eoip79/flake8_import_guard_automate_import_restriction/)\n\n## Features\n\n- \ud83d\udeab Detects forbidden imports in new and modified files\n- \ud83d\udd27 Configurable via .flake8 or pyproject.toml\n- \ud83d\udd0d Focuses on newly added imports in Git-versioned files\n- \ud83d\udd17 Seamless integration with existing Flake8 workflows\n\n## Motivation\n\nFlake8 Import Guard is designed to address several common challenges in Python development.\n\n- **Enforcing Security Measures**\n    - Prevent the use of potentially unsafe or deprecated modules, enhancing the overall security of your codebase.\n    - Prevent the import of forbidden external libraries, maintaining better control over your project's external dependencies.\n\n- **Dependency Management**\n    - Restrict and control project dependencies, reducing complexity and potential conflicts.\n\n- **License Compliance**\n    - Ensure compliance with licensing requirements by preventing the use of libraries with incompatible licenses.\n\n- **Performance Optimization**\n    - Avoid the use of heavyweight or inefficient imports that could impact performance.\n\n- **Coding Standards Enforcement**\n    - Maintain consistent coding standards across your project by enforcing specific import patterns.\n\n- **Gradual Deprecation of Legacy Code**\n    - Facilitate the phasing out of old modules or deprecated imports as your project evolves.\n\nBy using Flake8 Import Guard, development teams can proactively manage their codebase, ensuring better quality, security, and maintainability of their Python projects.\n\n## Installation\n\nYou can install Flake8 Import Guard using pip.\n\n```\npip install flake8-import-guard\n```\n\n## Usage\n\nOnce installed, Flake8 Import Guard will automatically be used by Flake8. You can run it using the standard Flake8 command.\n\n```\nflake8 path/to/your/code\n```\n\n## Recommended Integration\n\nIt is highly recommended to integrate Flake8 Import Guard into your pre-commit hooks and CI workflows. This ensures that import restrictions are enforced consistently across your development process, catching potential violations early and maintaining code quality standards.\n\n## Configuration\n\nYou can configure Flake8 Import Guard using Flake8's standard configuration system or through `pyproject.toml`.\n\nFor example, let's say you want to prohibit the use of `load_dotenv` and `subprocess` in your project. Here's how you would configure that.\n\n### Using Flake8 Configuration\n\nAdd the following to your `.flake8` file.\n\n```ini\n[flake8]\nforbidden_imports = load_dotenv,subprocess\n```\n\n### Using pyproject.toml\n\nAdd the following to your `pyproject.toml` file.\n\n```toml\n[tool.flake8-import-guard]\nforbidden_imports = [\n    \"load_dotenv\",\n    \"subprocess\"\n]\n```\n\n## Example\n\n### Configuration\n\nLet's say you have the following configuration in your `.flake8` file.\n\n```ini\n[flake8]\nforbidden_imports = load_dotenv,subprocess\n```\n\n### Sample Python File\n\nConsider the following Python file.\n\n```python\n# test_file.py\nimport os\nfrom datetime import datetime\n\nfrom subprocess import check_output  # Violation Module\n\nfrom dotenv import load_dotenv       # Violation Module\n\ndef main():\n    pass\n\nif __name__ == \"__main__\":\n    main()\n```\n\n### Execution and Result\n\nWhen you run Flake8 on this file, you'll get the following output.\n\n```console\n$ flake8 test_file.py\ntest_file.py:4:1: CPE001 Forbidden import found: subprocess.check_output\ntest_file.py:6:1: CPE001 Forbidden import found: dotenv.load_dotenv\n```\n\n## How It Works\n\n`flake8-import-guard` uses Git to detect changes in your codebase and enforce import restrictions. Here's a detailed explanation of its operation.\n\n\n1. For new files\n   - It checks all imports against the forbidden list.\n   - Any import found in the forbidden list is reported as a violation.\n\n2. For existing files\n   - It compares the current version with the last committed version to identify newly added imports.\n   - Only newly added imports that match the forbidden list are reported as violations.\n\n> [!IMPORTANT]\n> If a forbidden import already exists in the file at the time of introducing `flake8-import-guard`, it will not be detected as a violation. The plugin focuses only on new changes to prevent disruption to existing codebases.\n\n3. Violation reporting\n   - Only newly added imports that match the forbidden list are reported as violations.\n   - This approach allows for gradual implementation of import restrictions without causing immediate breaks in existing code.\n\nThis behavior ensures that introducing `flake8-import-guard` to an existing project doesn't immediately flag all existing forbidden imports, allowing for a smoother integration and gradual code improvement.\n\n\n## Capabilities and Limitations\n\n### What It Can Do\n\n- Detect newly added forbidden imports in both new and existing files\n- Work with Git-versioned projects\n- Configure forbidden imports through Flake8 config or pyproject.toml\n- Integrate seamlessly with existing Flake8 workflows\n\n### What It Cannot Do\n\n- Work in non-Git environments\n- Identify removed or modified imports (focus is on new additions only)\n- Detect indirect imports (e.g., imports within imported modules)\n\n## Error Codes\n\n- CPE001: Forbidden import found\n\n## Contributing\n\nContributions are welcome! Please feel free to submit a Pull Request.\nSee [CONTRIBUTING.md](https://github.com/K-dash/flake8-import-guard/blob/main/CONTRIBUTING.md) to get an idea of how contributions work.\n\n## License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Flake8 plugin to enforce import restrictions in Python projects.",
    "version": "1.0.0",
    "project_urls": {
        "Homepage": "https://qiita.com/inetcpl",
        "Repository": "https://github.com/K-dash/flake8-import-guard"
    },
    "split_keywords": [
        "flake8",
        " plugin",
        " import",
        " linter"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "8d1d4131f1367d4cba2b5b0872cd332b901da0219620621be23b79c4338188d9",
                "md5": "76e0bad059910326cd6c57f5761e5b03",
                "sha256": "af2aebedfc5733b67889780130e07b94f9feaf62ec9d74356c05841e3c71ebe7"
            },
            "downloads": -1,
            "filename": "flake8_import_guard-1.0.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "76e0bad059910326cd6c57f5761e5b03",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": "<4.0.0,>=3.8.1",
            "size": 6767,
            "upload_time": "2024-08-12T13:58:13",
            "upload_time_iso_8601": "2024-08-12T13:58:13.014362Z",
            "url": "https://files.pythonhosted.org/packages/8d/1d/4131f1367d4cba2b5b0872cd332b901da0219620621be23b79c4338188d9/flake8_import_guard-1.0.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "11c9b2c0627b1bb83237e9665cd25a0dc0938ba03f3f42e0c8770b714524d4d3",
                "md5": "b0fcd71cd627e5f3f2e5702759d7a806",
                "sha256": "b92476d2f6f737498a4a1e95ed0ad649a02dddc4657b164c926247f3254921df"
            },
            "downloads": -1,
            "filename": "flake8_import_guard-1.0.0.tar.gz",
            "has_sig": false,
            "md5_digest": "b0fcd71cd627e5f3f2e5702759d7a806",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": "<4.0.0,>=3.8.1",
            "size": 6265,
            "upload_time": "2024-08-12T13:58:14",
            "upload_time_iso_8601": "2024-08-12T13:58:14.207808Z",
            "url": "https://files.pythonhosted.org/packages/11/c9/b2c0627b1bb83237e9665cd25a0dc0938ba03f3f42e0c8770b714524d4d3/flake8_import_guard-1.0.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-08-12 13:58:14",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "K-dash",
    "github_project": "flake8-import-guard",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "flake8-import-guard"
}
        
Elapsed time: 1.64076s