### Project structure example Source: https://flake8.pycqa.org/en/latest/_sources/user/configuration.rst.txt Example directory tree showing typical project layout. ```text flake8 ├── docs │ ├── build │ └── source │ ├── _static │ ├── _templates │ ├── dev │ ├── internal │ └── user ├── flake8 │ ├── formatting │ ├── main │ ├── options │ └── plugins └── tests ├── fixtures │ └── config_files ├── integration └── unit ``` -------------------------------- ### Example of a comma-separated list configuration Source: https://flake8.pycqa.org/en/latest/_sources/plugin-development/plugin-parameters.rst.txt An example of how a comma-separated list input might be formatted in a configuration file. ```text E123,E124, E125, E126 ``` -------------------------------- ### Install tox with pip Source: https://flake8.pycqa.org/en/latest/internal/contributing.html Use `pip install --user tox` to install tox in the user site-packages directory. This is the recommended method when using the system Python or when you have pip available. ```bash pip install --user tox ``` -------------------------------- ### Create example formatter class inheriting BaseFormatter Source: https://flake8.pycqa.org/en/latest/_sources/plugin-development/formatters.rst.txt Start with a class that inherits from flake8.formatting.base.BaseFormatter and includes a docstring. This is the initial step; without implementing the format method, Flake8 will fail when using the plugin with --format=example. ```python from flake8.formatting import base class Example(base.BaseFormatter): """Flake8's example formatter.""" pass ``` -------------------------------- ### Use the prompt directive for command-line examples Source: https://flake8.pycqa.org/en/latest/internal/writing-documentation.html Use the `.. prompt::` directive to make command-line examples easier for users to copy and paste into their terminal. The example shows a bash prompt with two flake8 commands. ```reStructuredText .. prompt:: bash flake8 --select E123,W503 dir/ flake8 --ignore E24,W504 dir ``` -------------------------------- ### Configuring show-source in a config file Source: https://flake8.pycqa.org/en/latest/user/options.html Example of enabling show-source in a configuration file. ```ini show_source = True show-source = True ``` -------------------------------- ### Format option usage Source: https://flake8.pycqa.org/en/latest/user/options.html Examples of setting the formatter via command-line or configuration file. ```bash flake8 --format=pylint dir/ flake8 --format='%(path)s::%(row)d,%(col)d::%(code)s::%(text)s' dir/ ``` ```ini format=pylint format=%(path)s::%(row)d,%(col)d::%(code)s::%(text)s ``` -------------------------------- ### Configuring enable-extensions in a config file Source: https://flake8.pycqa.org/en/latest/user/options.html Example of enabling extensions in a configuration file. ```ini enable-extensions = H111, G123 enable_extensions = H111, G123 ``` -------------------------------- ### Use prompt directive for command-line examples Source: https://flake8.pycqa.org/en/latest/_sources/internal/writing-documentation.rst.txt Use the prompt directive in reStructuredText to format command-line examples for easy copying. ```restructuredtext .. prompt:: bash flake8 --select E123,W503 dir/ flake8 --ignore E24,W504 dir ``` -------------------------------- ### Configuring require-plugins in a config file Source: https://flake8.pycqa.org/en/latest/user/options.html Example of defining required plugins in a configuration file. ```ini require-plugins = flake8-2020 flake8-typing-extensions ``` -------------------------------- ### Configuring tee in a config file Source: https://flake8.pycqa.org/en/latest/user/options.html Example of enabling tee in a configuration file. ```ini tee = True ``` -------------------------------- ### Configuring jobs in a config file Source: https://flake8.pycqa.org/en/latest/user/options.html Example of setting the number of jobs in a configuration file. ```ini jobs = 8 ``` -------------------------------- ### Configuring statistics in a config file Source: https://flake8.pycqa.org/en/latest/user/options.html Example of enabling statistics in a configuration file. ```ini statistics = True ``` -------------------------------- ### setup.py for registering a Flake8 plugin Source: https://flake8.pycqa.org/en/latest/_sources/plugin-development/registering-plugins.rst.txt Full setup.py example for the flake8_example plugin, showing required dependencies, package metadata, and the placeholder entry_points configuration. ```python import setuptools requires = [ "flake8 > 3.0.0", ] flake8_entry_point = # ... setuptools.setup( name="flake8_example", license="MIT", version="0.1.0", description="our extension to flake8", author="Me", author_email="example@example.com", url="https://github.com/me/flake8_example", packages=[ "flake8_example", ], install_requires=requires, entry_points={ flake8_entry_point: [ 'X = flake8_example:ExamplePlugin', ], }, classifiers=[ "Framework :: Flake8", "Environment :: Console", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python", "Programming Language :: Python :: 3", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Software Development :: Quality Assurance", ], ) ``` -------------------------------- ### PEP-0257 docstring example from flake8.main.git.hook Source: https://flake8.pycqa.org/en/latest/_sources/internal/writing-code.rst.txt Example of a docstring that follows PEP-0257 style, with parameter descriptions starting on a new line and indented 4 spaces. The docstring describes the function's purpose, parameters, and return value. ```python # src/flake8/main/git.py def hook(lazy: bool = False, strict: bool = False) -> int: """Execute Flake8 on the files in git's index. Determine which files are about to be committed and run Flake8 over them to check for violations. :param lazy: Find files not added to the index prior to committing. This is useful if you frequently use ``git commit -a`` for example. This defaults to False since it will otherwise include files not in the index. :param strict: If True, return the total number of errors/violations found by Flake8. This will cause the hook to fail. :returns: Total number of errors found during the run. """ # NOTE(sigmavirus24): Delay import of application until we need it. from flake8.main import application app = application.Application() with make_temporary_directory() as tempdir: filepaths = list(copy_indexed_files_to(tempdir, lazy)) app.initialize(['.']) app.options.exclude = update_excludes(app.options.exclude, tempdir) app.run_checks(filepaths) app.report_errors() if strict: return app.result_count return 0 ``` -------------------------------- ### Highlighted entry point lines in setup.py Source: https://flake8.pycqa.org/en/latest/_sources/plugin-development/registering-plugins.rst.txt The specific lines from the setup.py example that show where the flake8 entry point is defined and registered. ```python flake8_entry_point = # ... setuptools.setup( # snip ... entry_points={ flake8_entry_point: [ 'X = flake8_example:ExamplePlugin', ], }, # snip ... ) ``` -------------------------------- ### Install Flake8 with pip Source: https://flake8.pycqa.org/en/latest/_sources/index.rst.txt Install Flake8 using the Python package installer. The first command installs for a specific Python version. The second command installs for the default Python installation. ```shell python -m pip install flake8 ``` ```shell python -m pip install flake8 ``` -------------------------------- ### Install Flake8 for the default Python version Source: https://flake8.pycqa.org/en/latest/index.html Use this command to install Flake8 for your default Python installation. ```bash python -m pip install flake8 ``` -------------------------------- ### Entry point for flake8.extension group Source: https://flake8.pycqa.org/en/latest/_sources/plugin-development/registering-plugins.rst.txt This setup.py entry_points configuration registers the ExamplePlugin in the flake8.extension group for plugins that add checks to Flake8. ```python setuptools.setup( # snip ... entry_points={ 'flake8.extension': [ 'X = flake8_example:ExamplePlugin', ], }, # snip ... ) ``` -------------------------------- ### Build documentation locally Source: https://flake8.pycqa.org/en/latest/_sources/internal/writing-documentation.rst.txt Run this command from the directory containing tox.ini to build the documentation locally. ```bash tox -e docs ``` -------------------------------- ### BaseFormatter.start() Source: https://flake8.pycqa.org/en/latest/_modules/flake8/formatting/base.html Prepares the formatter to receive input. Initializes output_fd if a filename is set. ```APIDOC ## BaseFormatter.start() ### Description Prepares the formatter to receive input. Initializes output_fd if a filename is set. ### Method Instance method ### Parameters None ### Returns None ``` -------------------------------- ### parse_comma_separated_list output example Source: https://flake8.pycqa.org/en/latest/_sources/internal/utils.rst.txt Shows the list that flake8.utils.parse_comma_separated_list returns for the input examples above. ```python ["E121", "W123", "F904"] ``` -------------------------------- ### flake8.api.legacy.get_style_guide Source: https://flake8.pycqa.org/en/latest/_sources/user/python-api.rst.txt Creates a StyleGuide instance with options corresponding to command-line options. Pass options like ignore, select, exclude, format to configure the style guide. ```APIDOC ## get_style_guide ### Description Creates a StyleGuide instance with options that correspond to command-line options. Options include ignore, select, exclude, format, etc. ### Parameters #### Keyword Arguments - **ignore** (list) - Optional - List of error codes to ignore, e.g. ['E24', 'W503'] - **select** (list) - Optional - List of error codes to select, e.g. ['E', 'W', 'F'] - **exclude** (list) - Optional - List of paths to exclude - **format** (str) - Optional - Output format, e.g. 'pylint' ### Request Example ```python from flake8.api import legacy as flake8 style_guide = flake8.get_style_guide(ignore=['E24', 'W503']) ``` ### Response Returns a StyleGuide instance. ``` -------------------------------- ### Application.initialize(argv) Source: https://flake8.pycqa.org/en/latest/_modules/flake8/main/application.html Initializes the application by finding plugins, registering options, and parsing command-line arguments. This method must be called before running checks. ```APIDOC ## Application.initialize(argv) ### Description Initializes the application to be run. This finds the plugins, registers their options, and parses the command-line arguments. ### Method initialize ### Parameters - **argv** (Sequence[str]) - Required - Command-line arguments to parse. ### Returns None ### Notes If the `--bug-report` option is set, prints debug information and exits with SystemExit(0). ``` -------------------------------- ### Passing options to get_style_guide Source: https://flake8.pycqa.org/en/latest/_sources/user/python-api.rst.txt Demonstrates passing command-line-like options (ignore, select, format) to get_style_guide. The legacy API does not enforce legacy behavior, so ignore and select can be combined. ```python style_guide = flake8.get_style_guide( ignore=['E24', 'W5'], select=['E', 'W', 'F'], format='pylint', ) ``` -------------------------------- ### Install tox with python -m pip Source: https://flake8.pycqa.org/en/latest/internal/contributing.html Use `python -m pip install --user tox` to install tox using a specific Python version, which may be required if only a particular Python interpreter is available. ```bash python -m pip install --user tox ``` -------------------------------- ### Verify Flake8 plugin installation Source: https://flake8.pycqa.org/en/latest/_sources/user/using-plugins.rst.txt Check the installed version of Flake8 to confirm that the plugin is registered and visible in the output. ```bash flake8 --version python -m flake8 --version ``` -------------------------------- ### Check option order with help command Source: https://flake8.pycqa.org/en/latest/_sources/internal/writing-documentation.rst.txt Verify the correct order for documenting new options by checking the output of the help command. ```bash flake8 --help ``` -------------------------------- ### StyleGuide.init_report Source: https://flake8.pycqa.org/en/latest/_modules/flake8/api/legacy.html Sets up a formatter for the Flake8 run. Accepts an optional reporter class that must be a subclass of flake8.formatter.BaseFormatter. ```APIDOC ## StyleGuide.init_report ### Description Sets up a formatter for this run of Flake8. If no reporter is provided, no action is taken. The reporter must be a subclass of flake8.formatter.BaseFormatter. ### Method init_report ### Signature init_report(self, reporter: type[formatter.BaseFormatter] | None = None) -> None ### Parameters - **reporter** (type[formatter.BaseFormatter] | None) - Optional - The formatter class to use. If None, the method returns without doing anything. ### Raises - **ValueError** - If reporter is not a subclass of flake8.formatter.BaseFormatter. ### Returns None ``` -------------------------------- ### Install Flake8 plugins via pip Source: https://flake8.pycqa.org/en/latest/_sources/user/using-plugins.rst.txt Use the appropriate pip command based on your Python environment to install a third-party plugin. ```bash pip install pip3 install python -m pip install python3 -m pip install python3.9 -m pip install ``` -------------------------------- ### Example ignore configuration in INI Source: https://flake8.pycqa.org/en/latest/_sources/internal/option_handling.rst.txt An example of how a user might specify a list of ignored error codes in a Flake8 configuration file. ```ini [flake8] ignore = # Reasoning E111, # Reasoning E711, # Reasoning E712, # Reasoning E121, # Reasoning E122, # Reasoning E123, # Reasoning E131, # Reasoning E251 ``` -------------------------------- ### flake8.main.cli.main(argv=None) Source: https://flake8.pycqa.org/en/latest/internal/cli.html Execute the main bit of the application. This handles the creation of an instance of Application, runs it, and then exits the application. ```APIDOC ## flake8.main.cli.main(argv=None) ### Description Execute the main bit of the application. This handles the creation of an instance of Application, runs it, and then exits the application. ### Parameters - **argv** (Sequence[str] | None) - Optional - The arguments to be passed to the application for parsing. ### Return Type int ``` -------------------------------- ### Entry point for error codes starting with X1 Source: https://flake8.pycqa.org/en/latest/plugin-development/registering-plugins.html Entry point line for a plugin that reports error codes starting with X1. ```python X1 = flake8_example:ExamplePlugin ``` -------------------------------- ### Entry point for error codes starting with X10 Source: https://flake8.pycqa.org/en/latest/plugin-development/registering-plugins.html Entry point line for a plugin that reports error codes starting with X10. ```python X10 = flake8_example:ExamplePlugin ``` -------------------------------- ### Find plugins entry point Source: https://flake8.pycqa.org/en/latest/_modules/flake8/plugins/finder.html Main function to discover all plugins, sort them, and validate requirements. ```python [docs] def find_plugins( cfg: configparser.RawConfigParser, opts: PluginOptions, ) -> list[Plugin]: """Discovers all plugins (but does not load them).""" ret = [*_find_importlib_plugins(), *_find_local_plugins(cfg)] # for determinism, sort the list ret.sort() _check_required_plugins(ret, opts.require_plugins) return ret ``` -------------------------------- ### Install tox with pip Source: https://flake8.pycqa.org/en/latest/_sources/internal/contributing.rst.txt Install tox using pip for the current user. Use the second variant to specify a Python version explicitly. ```bash pip install --user tox ``` ```bash python -m pip install --user tox ``` -------------------------------- ### get_style_guide function Source: https://flake8.pycqa.org/en/latest/_modules/flake8/api/legacy.html Provisions a StyleGuide for use by initializing an application instance and applying provided keyword arguments as options. ```python def get_style_guide(**kwargs: Any) -> StyleGuide: r"""Provision a StyleGuide for use. :param \*\*kwargs: Keyword arguments that provide some options for the StyleGuide. :returns: An initialized StyleGuide """ application = app.Application() application.plugins, application.options = parse_args([]) # We basically want application.initialize to be called but with these # options set instead before we make our formatter, notifier, internal # style guide and file checker manager. options = application.options for key, value in kwargs.items(): try: getattr(options, key) setattr(options, key, value) except AttributeError: LOG.error('Could not update option "%s"', key) application.make_formatter() application.make_guide() application.make_file_checker_manager([]) return StyleGuide(application) ``` -------------------------------- ### Install Flake8 for a specific Python version Source: https://flake8.pycqa.org/en/latest/index.html Use this command to install Flake8 on a specific version of Python to ensure it can parse language features associated with that version. ```bash python -m pip install flake8 ``` -------------------------------- ### Multi-line method definition example from flake8.formatting.base Source: https://flake8.pycqa.org/en/latest/_sources/internal/writing-code.rst.txt Shows a method definition with a docstring and a multi-line loop, illustrating the style for splitting code across lines. This example is from src/flake8/formatting/base.py. ```python # src/flake8/formatting/base.py def show_statistics(self, statistics): """Format and print the statistics.""" for error_code in statistics.error_codes(): stats_for_error_code = statistics.statistics_for(error_code) statistic = next(stats_for_error_code) count = statistic.count count += sum(stat.count for stat in stats_for_error_code) self._write(f'{count:<5} {error_code} {statistic.message}') ``` -------------------------------- ### StyleGuide.options Source: https://flake8.pycqa.org/en/latest/_modules/flake8/api/legacy.html Property that returns the application's options as an argparse.Namespace instance. ```APIDOC ## StyleGuide.options ### Description Return application's options. ### Method Property ### Endpoint flake8.api.legacy.StyleGuide.options ### Response #### Success Response - **argparse.Namespace** - An instance of argparse.Namespace containing parsed options. ``` -------------------------------- ### Multi-line function call example from flake8.main.options Source: https://flake8.pycqa.org/en/latest/_sources/internal/writing-code.rst.txt Shows the preferred style for splitting a function call across multiple lines: insert a new-line after the opening parenthesis. This example is from src/flake8/main/options.py. ```python # src/flake8/main/options.py add_option( '-v', '--verbose', default=0, action='count', parse_from_config=True, help='Print more information about what is happening in flake8.' ' This option is repeatable and will increase verbosity each ' 'time it is repeated.', ) ``` -------------------------------- ### Serve documentation locally with tox Source: https://flake8.pycqa.org/en/latest/_sources/internal/contributing.rst.txt Run a local server to view the documentation. Can be run in a separate terminal and continuously refreshed. ```bash tox -e serve-docs ``` -------------------------------- ### Commit message style example Source: https://flake8.pycqa.org/en/latest/_sources/internal/contributing.rst.txt Example commit message format: a short 50-character title, imperative voice, body lines no longer than 72 characters, and a final line referencing the issue. ```text Create a short title that is 50 characters long Ensure the title and commit message use the imperative voice. The commit and you are doing something. Also, please ensure that the body of the commit message does not exceed 72 characters. The body may have multiple paragraphs as necessary. The final line of the body references the issue appropriately. ``` -------------------------------- ### Implement format method in Example formatter Source: https://flake8.pycqa.org/en/latest/_sources/plugin-development/formatters.rst.txt Add the format method to the Example class so the formatter is usable. The method receives an error and returns a string representation. This completes the basic formatter; Flake8 calls handle, which by default calls format and then write. ```python class Example(base.BaseFormatter): """Flake8's example formatter.""" def format(self, error): return 'Example formatter: {0!r}'.format(error) ``` -------------------------------- ### Registering a check plugin with flake8.extension Source: https://flake8.pycqa.org/en/latest/plugin-development/registering-plugins.html Example setup.py entry_points using the 'flake8.extension' group for a plugin that adds checks. ```python setuptools.setup( # snip ... entry_points={ 'flake8.extension': [ 'X = flake8_example:ExamplePlugin', ], }, # snip ... ) ``` -------------------------------- ### BaseFormatter.beginning(filename) Source: https://flake8.pycqa.org/en/latest/_modules/flake8/formatting/base.html Notifies the formatter that processing of a file is starting. ```APIDOC ## BaseFormatter.beginning(filename) ### Description Notifies the formatter that processing of a file is starting. ### Method Instance method ### Parameters - **filename** (str) - Required - The name of the file that Flake8 is beginning to report results from. ### Returns None ``` -------------------------------- ### Configure local plugins with commas Source: https://flake8.pycqa.org/en/latest/_sources/user/configuration.rst.txt Example showing that commas can be used to separate local plugins in the configuration. ```ini [flake8:local-plugins] extension = MC1 = project.flake8.checkers:MyChecker1, MC2 = project.flake8.checkers:MyChecker2 report = MR1 = project.flake8.reporters:MyReporter1, MR2 = project.flake8.reporters:MyReporter2 ```