### Install dependencies Source: https://github.com/lyz-code/autoimport/blob/main/docs/contributing.md Install the project and configure pre-commits. ```bash make install ``` -------------------------------- ### Create a new branch Source: https://github.com/lyz-code/autoimport/blob/main/docs/contributing.md Start a new branch for your changes. ```bash git checkout -b my-new-feature-branch ``` -------------------------------- ### Install autoimport Source: https://github.com/lyz-code/autoimport/blob/main/README.md Use pip to install the autoimport package into your Python environment. ```bash pip install autoimport ``` -------------------------------- ### Example source code for autoimport Source: https://github.com/lyz-code/autoimport/blob/main/docs/index.md An example of Python source code containing missing and unused imports. ```python import requests def hello(names: Tuple[str]) -> None: for name in names: print(f"Hi {name}!") os.getcwd() ``` -------------------------------- ### Build documentation Source: https://github.com/lyz-code/autoimport/blob/main/docs/contributing.md Build the static documentation site locally. ```bash make docs ``` -------------------------------- ### Set up virtual environment Source: https://github.com/lyz-code/autoimport/blob/main/docs/contributing.md Configure a virtual environment for running tests. ```bash virtualenv -p `which python3.7` env source env/bin/activate ``` -------------------------------- ### Clone the repository Source: https://github.com/lyz-code/autoimport/blob/main/docs/contributing.md Initial steps to clone your fork and enter the directory. ```bash git clone git@github.com:/autoimport.git cd autoimport ``` -------------------------------- ### Report version information Source: https://github.com/lyz-code/autoimport/blob/main/docs/contributing.md Use this command to provide version details when opening an issue. ```bash python -c "import autoimport.version; print(autoimport.version.version_info())" ``` -------------------------------- ### Specifying Custom Config File Source: https://github.com/lyz-code/autoimport/blob/main/docs/index.md Use the --config-file flag to point to a specific configuration file. ```bash $: autoimport --config-file ~/.autoimport.toml file.py ``` -------------------------------- ### Run tests and linting Source: https://github.com/lyz-code/autoimport/blob/main/docs/contributing.md Execute the default test suite and linting. Use the ARGS variable to pass arguments to pytest. ```bash make ``` ```bash make test ARGS='-k test_markdownlint_passes' ``` -------------------------------- ### Format code Source: https://github.com/lyz-code/autoimport/blob/main/docs/contributing.md Run formatting tools to fix code style and imports. ```bash make format ``` -------------------------------- ### Run autoimport via command line Source: https://github.com/lyz-code/autoimport/blob/main/docs/index.md Execute autoimport on specific files or directories. ```bash $: autoimport file.py $: autoimport dir/ ``` -------------------------------- ### Configuration via pyproject.toml Source: https://context7.com/lyz-code/autoimport/llms.txt Autoimport can be configured through `pyproject.toml` to define custom common statements and other settings. Configuration is loaded automatically from the project directory. ```APIDOC ## Configuration via pyproject.toml Autoimport can be configured through `pyproject.toml` to define custom common statements and other settings. Configuration is loaded automatically from the project directory. ### Configuration Options - **disable_move_to_top** (bool) - Optional - If True, imports inside functions are left in place. Defaults to `false`. ### Common Statements The `[tool.autoimport.common_statements]` section allows defining custom mappings for module aliases or frequently used objects. #### Example `pyproject.toml` ```toml # pyproject.toml [tool.autoimport] # Disable moving imports to top (not recommended, but useful for circular imports) disable_move_to_top = false # Define custom common statements [tool.autoimport.common_statements] "np" = "import numpy as np" "pd" = "import pandas as pd" "plt" = "import matplotlib.pyplot as plt" "tf" = "import tensorflow as tf" "torch" = "import torch" "FooBar" = "from baz_qux import FooBar" "MyModel" = "from myproject.models import MyModel" ``` ``` -------------------------------- ### Configuring Common Statements Source: https://github.com/lyz-code/autoimport/blob/main/docs/index.md Define custom common statements in pyproject.toml or a standalone configuration file. ```toml # pyproject.toml [tool.autoimport.common_statements] "np" = "import numpy as np" "FooBar" = "from baz_qux import FooBar" ``` ```toml # .autoimport.toml [common_statements] "np" = "import numpy as np" "FooBar" = "from baz_qux import FooBar" ``` -------------------------------- ### Configure pre-commit for autoimport Source: https://github.com/lyz-code/autoimport/blob/main/docs/editor_integration.md Add these lines to the .pre-commit-config.yaml file to enable autoimport as a pre-commit hook. ```yaml repos: - repo: https://github.com/lyz-code/autoimport/ rev: master hooks: - id: autoimport ``` -------------------------------- ### Use Custom Configuration File with Autoimport CLI Source: https://context7.com/lyz-code/autoimport/llms.txt Specify a custom configuration file for autoimport to use when processing Python files. ```bash autoimport --config-file ~/.autoimport.toml file.py ``` -------------------------------- ### Run autoimport as a library Source: https://github.com/lyz-code/autoimport/blob/main/docs/index.md Use the fix_files function to process files or directories programmatically. ```python from autoimport import fix_files fix_files(["file.py", "dir/"]) ``` -------------------------------- ### Ignore __init__.py Files with Autoimport CLI Source: https://context7.com/lyz-code/autoimport/llms.txt Configure autoimport to skip processing __init__.py files, which often contain intentionally unused imports. ```bash autoimport --ignore-init-modules src/ ``` -------------------------------- ### Configure pre-commit hook Source: https://context7.com/lyz-code/autoimport/llms.txt Integrate autoimport into your pre-commit workflow to automatically fix imports before commits. ```yaml # .pre-commit-config.yaml repos: - repo: https://github.com/lyz-code/autoimport/ rev: master hooks: - id: autoimport # Optional: exclude certain files exclude: ^tests/fixtures/ # Optional: add arguments args: [--ignore-init-modules] ``` -------------------------------- ### Fix Files with Configuration Source: https://context7.com/lyz-code/autoimport/llms.txt Apply `fix_files` with a custom configuration, such as defining common statements for import resolution. ```python # With configuration config = { "common_statements": { "np": "import numpy as np" } } file = click.File("r+").convert("analysis.py", None, None) fix_files((file,), config=config) ``` -------------------------------- ### Autoimport Configuration in pyproject.toml Source: https://context7.com/lyz-code/autoimport/llms.txt Configure autoimport settings, including disabling import moving and defining custom common statements, within the `pyproject.toml` file. ```toml # pyproject.toml [tool.autoimport] # Disable moving imports to top (not recommended, but useful for circular imports) disable_move_to_top = false # Define custom common statements [tool.autoimport.common_statements] "np" = "import numpy as np" "pd" = "import pandas as pd" "plt" = "import matplotlib.pyplot as plt" "tf" = "import tensorflow as tf" "torch" = "import torch" "FooBar" = "from baz_qux import FooBar" "MyModel" = "from myproject.models import MyModel" ``` -------------------------------- ### Fix Multiple Files and Directories with Autoimport CLI Source: https://context7.com/lyz-code/autoimport/llms.txt Process multiple Python files and directories simultaneously using the autoimport command. ```bash autoimport file1.py file2.py mypackage/ ``` -------------------------------- ### Read from Stdin and Output to Stdout with Autoimport CLI Source: https://context7.com/lyz-code/autoimport/llms.txt Pipe Python code to autoimport for processing and receive the fixed code on standard output. ```bash cat file.py | autoimport - ``` -------------------------------- ### Command Line Interface Source: https://context7.com/lyz-code/autoimport/llms.txt The `autoimport` command-line tool can be used to process individual Python files or entire directories recursively to fix import statements. ```APIDOC ## Command Line Interface The `autoimport` command processes Python files to fix import statements. It accepts individual files or directories (which are processed recursively for all `.py` files). ### Usage Examples ```bash # Fix a single file autoimport file.py # Fix all Python files in a directory recursively autoimport src/ # Fix multiple files and directories autoimport file1.py file2.py mypackage/ # Use a custom configuration file autoimport --config-file ~/.autoimport.toml file.py # Ignore __init__.py files (which often have intentionally "unused" imports) autoimport --ignore-init-modules src/ # Keep unused imports (don't remove them) autoimport --keep-unused-imports file.py # Read from stdin and output to stdout cat file.py | autoimport - ``` ``` -------------------------------- ### Use built-in common statements Source: https://context7.com/lyz-code/autoimport/llms.txt Autoimport automatically recognizes and maps common imports without requiring manual configuration. ```python from autoimport import fix_code # BeautifulSoup from bs4 source = "soup = BeautifulSoup(html, 'html.parser')" print(fix_code(source)) # from bs4 import BeautifulSoup # # # soup = BeautifulSoup(html, 'html.parser') # Mock and patch from unittest.mock source = """ mock_obj = Mock() with patch('module.function'): pass """ print(fix_code(source)) # from unittest.mock import Mock # from unittest.mock import patch # # # mock_obj = Mock() # with patch('module.function'): # pass # Path from pathlib source = "config_path = Path('/etc/config')" print(fix_code(source)) # from pathlib import Path # # # config_path = Path('/etc/config') ``` -------------------------------- ### Resulting source code after autoimport Source: https://github.com/lyz-code/autoimport/blob/main/docs/index.md The source code after running autoimport, showing corrected imports. ```python import os from typing import Tuple def hello(names: Tuple[str]) -> None: for name in names: print(f"Hi {name}!") os.getcwd() ``` -------------------------------- ### Recursively Fix Python Files in Directory with Autoimport CLI Source: https://context7.com/lyz-code/autoimport/llms.txt Apply autoimport to all Python files within a specified directory and its subdirectories. ```bash autoimport src/ ``` -------------------------------- ### Basic Fix Code Usage Source: https://context7.com/lyz-code/autoimport/llms.txt Demonstrates the basic functionality of `fix_code` to manage imports in a Python source string. Requires `Tuple` from `typing`. ```python from autoimport import fix_code # Basic usage - fix missing and unused imports source = """ import requests def hello(names: Tuple[str]) -> None: for name in names: print(f"Hi {name}!") os.getcwd() """ fixed = fix_code(source) print(fixed) # Output: # import os # from typing import Tuple # # # def hello(names: Tuple[str]) -> None: # for name in names: # print(f"Hi {name}!") # ``` -------------------------------- ### Fix Multiple Files In Place Source: https://context7.com/lyz-code/autoimport/llms.txt Use `fix_files` to modify multiple Python files directly. Requires `click` for file handling. ```python from autoimport import fix_files import click # Fix multiple files in place file1 = click.File("r+").convert("module1.py", None, None) file2 = click.File("r+").convert("module2.py", None, None) fix_files((file1, file2)) # Files are modified in place ``` -------------------------------- ### Disabling Move to Top Source: https://github.com/lyz-code/autoimport/blob/main/docs/index.md Set disable_move_to_top to true in the configuration to prevent moving imports. ```toml [tool.autoimport] disable_move_to_top = true ``` -------------------------------- ### Keep Unused Imports with Autoimport CLI Source: https://context7.com/lyz-code/autoimport/llms.txt Instruct autoimport to retain unused import statements instead of removing them. ```bash autoimport --keep-unused-imports file.py ``` -------------------------------- ### Fix Code with Custom Common Statements Source: https://context7.com/lyz-code/autoimport/llms.txt Utilize `fix_code` with a custom configuration dictionary to define common statements like `np` for `numpy`. ```python from autoimport import fix_code # With custom common statements configuration source_with_numpy = """ data = np.array([1, 2, 3]) """ config = { "common_statements": { "np": "import numpy as np", "pd": "import pandas as pd" } } fixed = fix_code(source_with_numpy, config=config) print(fixed) # Output: # import numpy as np # # # data = np.array([1, 2, 3]) ``` -------------------------------- ### Ignore lines with noqa or fmt comments Source: https://context7.com/lyz-code/autoimport/llms.txt Use specific comments to prevent autoimport from moving or removing import statements. ```python # Prevent an import from being moved to the top a = 1 from os import getcwd # noqa: autoimport getcwd() # Prevent inline import/debug statement from being moved def debug_function(): import pdb; pdb.set_trace() # fmt: skip return 'debugging' # Keep an import that appears unused but is used dynamically from mymodule import handler # noqa: autoimport # handler is loaded dynamically via getattr() ``` -------------------------------- ### Fix Code with Disabled Move to Top Source: https://context7.com/lyz-code/autoimport/llms.txt Configure `fix_code` using a dictionary to disable the automatic moving of import statements to the top of the file. ```python from autoimport import fix_code # Disable moving imports to top source_with_inline = """ import requests requests.get('https://example.com') def test(): import os os.getcwd() """ config = {"disable_move_to_top": True} fixed = fix_code(source_with_inline, config=config) # Imports inside functions are left in place ``` -------------------------------- ### Preventing Import Movement Source: https://github.com/lyz-code/autoimport/blob/main/docs/index.md Use # noqa: autoimport or # fmt: skip to keep an import statement in its current position. ```python a = 1 from os import getcwd # noqa: autoimport getcwd() ``` -------------------------------- ### Fix Files Keeping Unused Imports Source: https://context7.com/lyz-code/autoimport/llms.txt Use `fix_files` with `keep_unused_imports=True` to preserve unused imports, particularly useful for `__init__.py` files. ```python # With keep_unused_imports for __init__.py init_file = click.File("r+").convert("mypackage/__init__.py", None, None) fix_files((init_file,), keep_unused_imports=True) ``` -------------------------------- ### Fix Single Python File with Autoimport CLI Source: https://context7.com/lyz-code/autoimport/llms.txt Use the autoimport command-line tool to fix import statements in a single Python file. ```bash autoimport file.py ``` -------------------------------- ### fix_files Function Source: https://context7.com/lyz-code/autoimport/llms.txt The `fix_files` function processes multiple file objects, fixing their import statements in place. When reading from stdin, it returns the fixed code as a string instead of modifying files. ```APIDOC ## fix_files Function The `fix_files` function processes multiple file objects, fixing their import statements in place. When reading from stdin, it returns the fixed code as a string instead of modifying files. ### Parameters - **files** (iterable of file objects) - Required - An iterable of file objects to process. - **config** (dict) - Optional - A dictionary containing configuration options. See `Configuration via pyproject.toml` for details. - **keep_unused_imports** (bool) - Optional - If True, unused imports will not be removed. ### Request Example ```python from autoimport import fix_files import click # Fix multiple files in place # Assuming module1.py and module2.py exist and are writable # file1 = click.File("r+").convert("module1.py", None, None) # file2 = click.File("r+").convert("module2.py", None, None) # fix_files((file1, file2)) # With configuration config = { "common_statements": { "np": "import numpy as np" } } # Assuming analysis.py exists and is writable # file = click.File("r+").convert("analysis.py", None, None) # fix_files((file,), config=config) # With keep_unused_imports for __init__.py # Assuming mypackage/__init__.py exists and is writable # init_file = click.File("r+").convert("mypackage/__init__.py", None, None) # fix_files((init_file,), keep_unused_imports=True) ``` ``` -------------------------------- ### Handle TYPE_CHECKING blocks Source: https://context7.com/lyz-code/autoimport/llms.txt Autoimport preserves imports inside TYPE_CHECKING blocks to prevent circular import issues. ```python from autoimport import fix_code source = """ import os from typing import TYPE_CHECKING if TYPE_CHECKING: from .model import Book os.getcwd() def read_book(book: Book): pass """ fixed = fix_code(source) # The TYPE_CHECKING block is preserved as-is print(fixed) # import os # from typing import TYPE_CHECKING # # if TYPE_CHECKING: # from .model import Book # # # os.getcwd() # # # def read_book(book: Book): # pass ``` -------------------------------- ### Fix Code Keeping Unused Imports Source: https://context7.com/lyz-code/autoimport/llms.txt Use the `keep_unused_imports=True` option with `fix_code` to prevent the removal of unused import statements. ```python from autoimport import fix_code # Keep unused imports (useful for __init__.py files) source_with_unused = """ import gzip import hashlib csv_writer = csv.DictWriter(filename, fieldnames=["name", "age"]) gzip.open(filename, 'wb') """ fixed = fix_code(source_with_unused, keep_unused_imports=True) print(fixed) # Output: # import gzip # import hashlib # # import csv # # # csv_writer = csv.DictWriter(filename, fieldnames=["name", "age"]) # gzip.open(filename, 'wb') ``` -------------------------------- ### fix_code Function Source: https://context7.com/lyz-code/autoimport/llms.txt The `fix_code` function is the core library function that fixes Python source code by adding missing imports, removing unused imports, and moving import statements to the top of the file. It returns the corrected source code as a string. ```APIDOC ## fix_code Function The `fix_code` function is the core library function that fixes Python source code by adding missing imports, removing unused imports, and moving import statements to the top of the file. It returns the corrected source code as a string. ### Parameters - **source** (str) - Required - The Python source code as a string. - **config** (dict) - Optional - A dictionary containing configuration options. See `Configuration via pyproject.toml` for details. - **keep_unused_imports** (bool) - Optional - If True, unused imports will not be removed. ### Request Example ```python from autoimport import fix_code # Basic usage - fix missing and unused imports source = """ import requests def hello(names: Tuple[str]) -> None: for name in names: print(f"Hi {name}!") os.getcwd() """ fixed = fix_code(source) print(fixed) # With custom common statements configuration source_with_numpy = """ data = np.array([1, 2, 3]) """ config = { "common_statements": { "np": "import numpy as np", "pd": "import pandas as pd" } } fixed = fix_code(source_with_numpy, config=config) print(fixed) # Keep unused imports (useful for __init__.py files) source_with_unused = """ import gzip import hashlib csv_writer = csv.DictWriter(filename, fieldnames=["name", "age"]) gzip.open(filename, 'wb') """ fixed = fix_code(source_with_unused, keep_unused_imports=True) print(fixed) # Disable moving imports to top source_with_inline = """ import requests requests.get('https://example.com') def test(): import os os.getcwd() """ config = {"disable_move_to_top": True} fixed = fix_code(source_with_inline, config=config) ``` ### Response Example ```python # Output for basic usage: # import os # from typing import Tuple # # def hello(names: Tuple[str]) -> None: # for name in names: # print(f"Hi {name}!") # # os.getcwd() # Output for custom common statements: # import numpy as np # # # data = np.array([1, 2, 3]) # Output for keep_unused_imports=True: # import gzip # import hashlib # # import csv # # # csv_writer = csv.DictWriter(filename, fieldnames=["name", "age"]) # gzip.open(filename, 'wb') ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.