Flake8 Class Attributes Order
An extension for Flake8 that enforces a consistent order for attributes within Python classes. It analyzes various attribute types, including docstrings, properties, methods, nested classes, and constants, and can also detect Django model fields. The current version is 0.3.0, and it maintains an active release cadence with regular updates.
Warnings
- breaking Version 0.3.0 dropped support for Python 3.8. Ensure your environment uses Python 3.9 or newer.
- breaking Version 0.2.0 dropped support for Python 3.7. Ensure your environment uses Python 3.8 or newer to use this version.
- gotcha To enable stricter attribute ordering checks, set `use_class_attributes_order_strict_mode = True` in your `flake8` configuration file (e.g., `setup.cfg`, `tox.ini`, or `.flake8`).
- gotcha The plugin introduces specific error codes, such as CCE001 ('Wrong class attributes order') and CCE002 ('Class has class level logic'). If you wish to ignore these, you must explicitly add them to the `ignore` list in your Flake8 configuration.
- gotcha Custom attribute orders can be defined using the `class_attributes_order` setting in the Flake8 configuration file. The default order is specific, and deviations will be reported.
Install
-
pip install flake8-class-attributes-order
Imports
- plugin
Install 'flake8-class-attributes-order'; it's automatically discovered by Flake8.
Quickstart
import os
# Create a dummy python file for flake8 to check
with open('my_module.py', 'w') as f:
f.write("""class MyClass:
FOO = 1
def __init__(self):
self.bar = 2
def method_a(self):
pass
""")
# Create a flake8 configuration file to enable strict mode (optional, but good for demo)
with open('setup.cfg', 'w') as f:
f.write("[flake8]\nuse_class_attributes_order_strict_mode = True\n")
# Run flake8. Note: flake8's exit code is non-zero if errors are found.
# We use os.system for demonstration; in a real CI, you'd just run 'flake8'.
print("Running flake8 without strict mode (default order):")
os.system("flake8 my_module.py")
print("\nRunning flake8 with strict mode (via setup.cfg):")
os.system("flake8 my_module.py")
# Clean up
os.remove('my_module.py')
os.remove('setup.cfg')