### setup.cfg Example Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/configuration.md Example of autopep8 configuration in a setup.cfg file. ```ini [autopep8] max-line-length = 100 aggressive = 2 ignore = E226,E24,W50 exclude = .git,__pycache__,docs ``` -------------------------------- ### Configuration file example (pycodestyle) Source: https://github.com/hhatto/autopep8/blob/main/README.rst Example of a configuration file for pycodestyle. ```ini [pycodestyle] max_line_length = 120 ignore = E501 ``` -------------------------------- ### Configuration file example (pyproject.toml) Source: https://github.com/hhatto/autopep8/blob/main/README.rst Example of a configuration file for pyproject.toml. ```toml [tool.autopep8] max_line_length = 120 ignore = "E501,W6" # or ["E501", "W6"] in-place = true recursive = true aggressive = 3 ``` -------------------------------- ### pyproject.toml Example Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/configuration.md Example of autopep8 configuration in a pyproject.toml file. ```toml [tool.autopep8] max-line-length = 100 aggressive = 2 ignore = "E226,E24,W50" exclude = ".git,__pycache__,docs" ``` -------------------------------- ### CI/CD Pipeline Examples Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/README.md Examples of using autopep8 in a CI/CD pipeline for checking and fixing formatting. ```bash # Check formatting without modifying autopep8 --diff --exit-code src/ || exit 1 # Fix formatting if needed autopep8 --in-place --recursive src/ ``` -------------------------------- ### Token Namedtuple Example Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/types.md An example demonstrating how to generate and iterate over tokens using autopep8. ```python import autopep8 import tokenize code = "x = 1" tokens = autopep8.generate_tokens(code) # Iterate over cached tokens for token_info in tokens: print(f"Type: {tokenize.tok_name[token_info.type]}, " f"String: {token_info.string}") ``` -------------------------------- ### LineEndingWrapper Example Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/api-reference.md Example of using LineEndingWrapper to wrap stdout and write with specific line endings. ```python import autopep8 import sys # Wrap stdout to use specific line endings wrapped = autopep8.LineEndingWrapper(sys.stdout, newline='\r\n') wrapped.write("Hello\nWorld") # Writes with CRLF ``` -------------------------------- ### Example of code before and after autopep8 formatting Source: https://github.com/hhatto/autopep8/blob/main/README.rst This snippet shows a Python code example before and after being processed by autopep8, demonstrating its formatting capabilities. ```python import math, sys; def example1(): ####This is a long comment. This should be wrapped to fit within 72 characters. some_tuple=( 1,2, 3,'a' ); some_variable={'long':'Long code lines should be wrapped within 79 characters.', 'other':[math.pi, 100,200,300,9876543210,'This is a long string that goes on'], 'more':{'inner':'This whole logical line should be wrapped.',some_tuple:[1, 20,300,40000,500000000,60000000000000000]}} return (some_tuple, some_variable) def example2(): return {'has_key() is deprecated':True}.has_key({'f':2}.has_key('')); class Example3( object ): def __init__ ( self, bar ): #Comments should have a space after the hash. if bar : bar+=1; bar=bar* bar ; return bar else: some_string = """ Indentation in multiline strings should not be touched. Only actual code should be reindented. """ return (sys.path, some_string) ``` ```python import math import sys def example1(): # This is a long comment. This should be wrapped to fit within 72 # characters. some_tuple = (1, 2, 3, 'a') some_variable = { 'long': 'Long code lines should be wrapped within 79 characters.', 'other': [ math.pi, 100, 200, 300, 9876543210, 'This is a long string that goes on'], 'more': { 'inner': 'This whole logical line should be wrapped.', some_tuple: [ 1, 20, 300, 40000, 500000000, 60000000000000000]}} return (some_tuple, some_variable) def example2(): return ('' in {'f': 2}) in {'has_key() is deprecated': True} class Example3(object): def __init__(self, bar): # Comments should have a space after the hash. if bar: bar += 1 bar = bar * bar return bar else: some_string = """ Indentation in multiline strings should not be touched. Only actual code should be reindented. """ return (sys.path, some_string) ``` -------------------------------- ### Combined with other options Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/configuration.md Example of combining --line-range with --in-place and --aggressive options. ```bash # Combined with other options autopep8 --in-place --aggressive --line-range 1 50 file.py ``` -------------------------------- ### Aggressive Fixes Example Source: https://github.com/hhatto/autopep8/blob/main/README.rst Demonstrates how to enable more aggressive fixes by using the --aggressive option. ```bash $ autopep8 --aggressive ``` -------------------------------- ### fix_e262() Example Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/fix-methods-reference.md Demonstrates fixing inline comments that do not start with '# '. ```python # Before x = 1 #comment # After x = 1 # comment ``` -------------------------------- ### Example Instance Fixer Function (Whitespace after '(') Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/types.md Example implementation of an instance fixer method to correct whitespace after an opening parenthesis. ```python def fix_e201(self, result: dict) -> Optional[List[int]]: """Fix whitespace after '('.""" line_index = result['line'] - 1 # Modify self.source and return affected lines or None return None # None means only the reported line was modified ``` -------------------------------- ### fix_file() Example Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/api-reference.md Illustrates formatting a file in-place and retrieving formatted code without modifying the file. ```python import autopep8 # Format file in-place options = autopep8.parse_args(['--in-place', 'myfile.py']) autopep8.fix_file('myfile.py', options=options) # Get formatted code without modifying file formatted = autopep8.fix_file('myfile.py') print(formatted) ``` -------------------------------- ### fix_lines() Example Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/api-reference.md Shows how to format a list of source code lines using the fix_lines function. ```python import autopep8 lines = [ 'import sys, math\n', 'x=1\n', 'y = 2\n' ] options = autopep8.parse_args(['dummy.py']) fixed = autopep8.fix_lines(lines, options, filename='dummy.py') print(fixed) ``` -------------------------------- ### Black-Compatible Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/configuration.md Example Python code for configuring autopep8 programmatically to be compatible with Black's formatting standards. ```python options = autopep8.parse_args([ '--aggressive', '--aggressive', '--max-line-length', '88', '--ignore', 'E203,E501,W503', 'file.py' ]) ``` -------------------------------- ### Creating Options Programmatically Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/configuration.md Examples of creating autopep8 options programmatically using parse_args, a dictionary, or by modifying parsed options. ```python import autopep8 # Method 1: Parse command-line style arguments options = autopep8.parse_args([ '--aggressive', '--aggressive', '--max-line-length', '100', '--ignore', 'E226,E24', 'dummy.py' ]) # Method 2: Create options dict and pass to fix_code options_dict = { 'aggressive': 2, 'max_line_length': 100, 'ignore': ['E226', 'E24'], } fixed = autopep8.fix_code(code, options=options_dict) # Method 3: Modify parsed options options = autopep8.parse_args(['dummy.py']) options.aggressive = 2 options.max_line_length = 100 fixed = autopep8.fix_code(code, options=options) ``` -------------------------------- ### Creating Options Namespace Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/types.md Examples of creating the options namespace, either from command-line arguments, manually, or from a dictionary. ```python import argparse # From command-line arguments options = autopep8.parse_args(['--aggressive', '--max-line-length', '100', 'file.py']) # Creating manually options = argparse.Namespace( ignore=['E226', 'E24', 'W50', 'W690'], select=[], max_line_length=79, aggressive=0, indent_size=4, # ... other fields ) # From dict (used internally) options_dict = { 'aggressive': 1, 'max_line_length': 100, } fixed = autopep8.fix_code(source, options=options_dict) ``` -------------------------------- ### Example Instance Fixer Function (Multiple Statements) Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/types.md Example implementation of an instance fixer method to fix multiple statements on a single line using a semicolon, leveraging logical line context. ```python def fix_e702(self, result: dict, logical: Tuple) -> Optional[List[int]]: """Fix multiple statements on one line (semicolon).""" # Uses logical line to understand full statement context pass ``` -------------------------------- ### fix_code() Example Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/api-reference.md Demonstrates how to use the fix_code function to format a string of Python code. ```python import autopep8 code = ''' import sys, math x=1 y = 2 ''' fixed = autopep8.fix_code(code) print(fixed) ``` -------------------------------- ### Example Global Fixer Function Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/types.md Example implementation of a global fixer function to fix indentation containing mixed spaces and tabs. ```python def fix_e101(source: str) -> str: """Fix indentation contains mixed spaces and tabs.""" return reindent(source, indent_size=4) ``` -------------------------------- ### Verbose Progress Messages Example Source: https://github.com/hhatto/autopep8/blob/main/README.rst Enables verbose progress messages for large files. ```bash $ autopep8 -v ``` -------------------------------- ### fix_e722 Example Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/fix-methods-reference.md Demonstrates how autopep8 changes bare 'except:' to 'except Exception:'. ```python # Before try: risky() except: pass # After try: risky() except Exception: pass ``` -------------------------------- ### Error Result Dictionary Example Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/types.md An example of an error result dictionary and how the fix method name is derived. ```python # When FixPEP8.fix() is called internally, it receives results like: result = { 'line': 42, 'column': 79, 'code': 'E501', 'info': 'line too long (85 > 79 characters)', 'id': 'E501' } # The fix method name is derived from id: fix_e501() ``` -------------------------------- ### fix_e721 Example Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/fix-methods-reference.md Demonstrates how autopep8 converts type comparison to isinstance(). ```python # Before if type(x) == str: pass # After if isinstance(x, str): pass ``` -------------------------------- ### Example of Correct and Incorrect Configuration Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/types.md Demonstrates correct and incorrect ways to pass configuration options as a dictionary to autopep8.fix_code(), showing potential ValueError. ```python import autopep8 # Correct options_dict = { 'aggressive': 2, 'max_line_length': 100, 'ignore': ['E226', 'E24'], # list, not string } fixed = autopep8.fix_code(code, options=options_dict) # Incorrect - raises ValueError options_dict = { 'aggressive': '2', # Should be int, not str 'ignore': 'E226,E24', # Should be list, not str } # This will raise: "Option 'aggressive' should not be a string" ``` -------------------------------- ### Experimental Functionality Example Source: https://github.com/hhatto/autopep8/blob/main/README.rst Enables experimental functionality, such as shortening code lines based on length. ```bash $ autopep8 --experimental ``` -------------------------------- ### Fix only lines 10-20 Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/configuration.md Example of using the --line-range option to specify a subset of lines for fixing. ```bash # Fix only lines 10-20 autopep8 --line-range 10 20 file.py ``` -------------------------------- ### Select Specific Fixes Example Source: https://github.com/hhatto/autopep8/blob/main/README.rst Shows how to enable only a subset of fixes using the --select option. ```bash $ autopep8 --select=E1,W1 ``` -------------------------------- ### Parallel Processing Example Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/README.md Illustrates how to use the --jobs argument to enable parallel processing of multiple files. ```python options = autopep8.parse_args(['--jobs', '4', '--in-place'] + files) ``` -------------------------------- ### E712 - Comparison with True/False Example Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/errors.md Illustrates simplifying comparisons with True/False/0/1 to a boolean check. ```python # Before if x == True: pass # After (Level 1) if x is True: pass # After (Level 2) if x: pass ``` -------------------------------- ### fix_e302() Example Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/fix-methods-reference.md Illustrates adding blank lines between top-level function definitions. ```python # Before def foo(): pass def bar(): # E302: expected 2 blank lines pass # After def foo(): pass def bar(): pass ``` -------------------------------- ### fix_e704 Example Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/fix-methods-reference.md Demonstrates how autopep8 converts lambda assignment to a function definition. ```python # Before square = lambda x: x ** 2 # After def square(x): return x ** 2 ``` -------------------------------- ### fix_e401() Example Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/fix-methods-reference.md Demonstrates splitting multiple imports on a single line into separate import statements. ```python # Before import sys, os, re # After import sys import os import re ``` -------------------------------- ### Fix only indentation and blank line issues Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/configuration.md Example of using the --select option to fix only specific error codes related to indentation and blank lines. ```bash # Fix only indentation and blank line issues autopep8 --select=E1,E3 file.py ``` -------------------------------- ### Exclude test files Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/configuration.md Example of using --exclude to skip files matching specific patterns, such as test files. ```bash # Exclude test files autopep8 --exclude "*_test.py,test_*" --in-place --recursive src/ ``` -------------------------------- ### fix_e713 Example Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/fix-methods-reference.md Demonstrates how autopep8 changes 'not x in y' to 'x not in y'. ```python # Before if not item in list: pass # After if item not in list: pass ``` -------------------------------- ### E201 - Whitespace after '(' Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/errors.md Example of whitespace after an opening parenthesis. ```python # Before result = function( x, y) # After result = function(x, y) ``` -------------------------------- ### E203 - Whitespace before ':' Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/errors.md Example of whitespace before a colon in a slice or type annotation. ```python # Before x = list[1 : 5] # After x = list[1:5] ``` -------------------------------- ### Fix everything except long lines and W50x codes Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/configuration.md Example of using the --ignore option to exclude specific error codes while fixing others. ```bash # Fix everything except long lines and W50x codes autopep8 --ignore=E501,W50 file.py ``` -------------------------------- ### fix_e225() Example Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/fix-methods-reference.md Adds missing spaces around operators (=, +, etc.). ```python def fix_e225(self, result) -> Optional[List[int]] # Before (E225) x=1+2 # After x = 1 + 2 ``` -------------------------------- ### Exclude multiple patterns Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/configuration.md Example of using the --exclude option with multiple fnmatch glob patterns to skip files and directories. ```bash # Exclude multiple patterns autopep8 --in-place --recursive --exclude ".git,__pycache__,.venv" . ``` -------------------------------- ### E722 - Do not use bare 'except:' Example Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/errors.md Demonstrates fixing bare 'except:' blocks by changing them to catch 'Exception'. ```python # Before try: risky_operation() except: pass # After try: risky_operation() except Exception: pass ``` -------------------------------- ### fix_e702 Example Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/fix-methods-reference.md Demonstrates how autopep8 fixes multiple statements on one line separated by a semicolon. ```python # Before x = 1; y = 2; z = 3 # After x = 1 y = 2 z = 3 ``` -------------------------------- ### fix_e701 Example Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/fix-methods-reference.md Demonstrates how autopep8 fixes multiple statements on one line separated by a colon. ```python # Before if True: x = 1 # After if True: x = 1 ``` -------------------------------- ### Fix only E4 codes (import-related) Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/configuration.md Example of using --select to target only import-related error codes. ```bash # Fix only E4 codes (import-related) autopep8 --select=E4 file.py ``` -------------------------------- ### Strict (Aggressive Level 2) Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/configuration.md Example Python code for configuring autopep8 programmatically with aggressive level 2 and a strict max line length. ```python options = autopep8.parse_args([ '--aggressive', '--aggressive', '--max-line-length', '79', 'file.py' ]) ``` -------------------------------- ### fix_e711 Example Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/fix-methods-reference.md Demonstrates how autopep8 changes comparison with None to use 'is None' or 'is not None'. ```python # Before if x == None: pass # After if x is None: pass ``` -------------------------------- ### Moderate (Aggressive Level 1) Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/configuration.md Example Python code for configuring autopep8 programmatically with aggressive level 1, setting max line length, and ignoring specific codes. ```python options = autopep8.parse_args([ '--aggressive', '--max-line-length', '88', '--ignore', 'E501', # Allow longer lines 'file.py' ]) ``` -------------------------------- ### fix_e301() Example Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/fix-methods-reference.md Shows adding a missing blank line before a nested function definition. ```python # Before def outer(): def inner(): # E301: expected 1 blank line pass # After def outer(): def inner(): pass ``` -------------------------------- ### Example Import Statement Representation Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/types.md Illustrates how autopep8's 'self.imports' dictionary would be populated for a given source code snippet. ```python # For source: import sys import os from pathlib import Path # self.imports dict in FixPEP8 would be: { "import sys\n": 0, "import os\n": 1, "from pathlib import Path\n": 2, } ``` -------------------------------- ### W605 - Invalid escape sequence Example Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/errors.md Demonstrates converting a string with an invalid escape sequence to a raw string or escaping the backslash. ```python # Before path = 'C:\Users\name' # After path = r'C:\Users\name' # or path = 'C:\\Users\\name' ``` -------------------------------- ### Pattern 2: Multi-line fix Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/fix-methods-reference.md Example of a fix method that inserts blank lines before a specific line. ```python def fix_e302(self, result): line_index = result['line'] - 1 # Insert blank lines before this line for _ in range(blank_lines_needed): self.source.insert(line_index, '\n') return list(range(line_index, line_index + blank_lines_needed)) ``` -------------------------------- ### E101 - Indentation contains mixed spaces and tabs Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/errors.md Example of mixed spaces and tabs for indentation. ```python # Before (mixed) def foo(): x = 1 # spaces y = 2 # tab # After def foo(): x = 1 y = 2 ``` -------------------------------- ### Conservative (Whitespace Only) Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/configuration.md Example Python code for configuring autopep8 programmatically to perform only whitespace fixes, ignoring long lines and binary operator breaks. ```python options = autopep8.parse_args([ '--ignore', 'E501,W503,W504', # Skip long lines and binary operator breaks 'file.py' ]) ``` -------------------------------- ### fix_e502() Example Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/fix-methods-reference.md Shows removing a redundant backslash used for line continuation inside brackets. ```python # Before (E502) result = (x + \ y + z) # After result = (x + y + z) ``` -------------------------------- ### Pattern 1: Simple line replacement Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/fix-methods-reference.md Example of a fix method that performs a simple line replacement using regex. ```python def fix_e201(self, result): line_index = result['line'] - 1 line = self.source[line_index] # Remove extraneous space after '(' fixed_line = re.sub(r'\(\s+', '(', line) self.source[line_index] = fixed_line return None ``` -------------------------------- ### E714 - Test for object identity with 'is not' Example Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/errors.md Shows how to fix 'not x is y' to the proper 'x is not y' syntax. ```python # Before if not x is None: pass # After if x is not None: pass ``` -------------------------------- ### Disabled Sections Example Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/README.md Demonstrates how to use special comments to disable autopep8 formatting for specific sections of code. ```python # autopep8: disable badly_formatted = stuff( here, is, ignored ) # autopep8: enable ``` -------------------------------- ### Upgrade setuptools Source: https://github.com/hhatto/autopep8/blob/main/README.rst If you encounter pkg_resources.DistributionNotFound, try upgrading setuptools. ```bash $ pip install --upgrade setuptools ``` -------------------------------- ### E713 - Test for membership with 'not in' Example Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/errors.md Demonstrates changing 'not x in y' to the correct 'x not in y' syntax. ```python # Before if not x in list: pass # After if x not in list: pass ``` -------------------------------- ### Fixing Specific Errors with autopep8 Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/errors.md Examples of using the --select and --ignore flags to control which errors autopep8 fixes. ```bash # Fix only indentation (E1xx) autopep8 --select=E1 file.py ``` ```bash # Fix imports and indentation autopep8 --select=E1,E4 file.py ``` ```bash # Fix everything except long lines autopep8 --ignore=E501 file.py ``` ```bash # Fix only whitespace (E2xx, W2xx) autopep8 --select=E2,W2 file.py ``` -------------------------------- ### E721 - Do not compare types; use 'isinstance()' Example Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/errors.md Illustrates converting type comparisons like 'type(x) == SomeClass' to 'isinstance(x, SomeClass)'. ```python # Before if type(x) == MyClass: pass # After if isinstance(x, MyClass): pass ``` -------------------------------- ### Pattern 3: Logical line fix Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/fix-methods-reference.md Example of a fix method that processes all lines within a logical block. ```python def fix_e702(self, result, logical): if logical: start, end = logical[0] - 1, logical[1] - 1 # Process all lines in the logical block modified = [] # ... modifications ... return modified return None ``` -------------------------------- ### main() Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/api-reference.md Command-line entry point for autopep8. Processes files and returns an exit code. ```python def main(argv=None, apply_config=True) -> int: ... import autopep8 import sys # Run autopep8 from command line arguments exit_code = autopep8.main(['autopep8', '--in-place', 'myfile.py']) sys.exit(exit_code) ``` -------------------------------- ### E231 - Missing whitespace after ',' Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/errors.md Example of missing whitespace after a comma. ```python ``` -------------------------------- ### parse_args() Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/api-reference.md Parses command-line arguments and returns an options namespace object. Optionally applies configuration from files (setup.cfg, .pep8, pyproject.toml). ```python def parse_args(arguments, apply_config=False) -> argparse.Namespace: ... import autopep8 # Parse basic arguments args = autopep8.parse_args(['--in-place', '--aggressive', 'myfile.py']) print(args.in_place) # True print(args.aggressive) # 1 print(args.files) # ['myfile.py'] # With config file parsing args = autopep8.parse_args(['--in-place', 'myfile.py'], apply_config=True) ``` -------------------------------- ### E111 - Indentation is not a multiple of four Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/errors.md Example of indentation not being a multiple of four. ```python # Before def foo(): x = 1 # 3 spaces instead of 4 # After def foo(): x = 1 # 4 spaces ``` -------------------------------- ### fix_e201() through fix_e204() Example Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/fix-methods-reference.md Removes extraneous whitespace around brackets. ```python def fix_e201(self, result) -> Optional[List[int]] # Before (E201) result = function( x, y ) # After result = function(x, y) ``` -------------------------------- ### fix_e251() Example Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/fix-methods-reference.md Removes spaces around '=' in function parameter defaults. ```python def fix_e251(self, result) -> Optional[List[int]] # Before def func(x = 1, y= 2): pass # After def func(x=1, y=2): pass ``` -------------------------------- ### Running tests directly Source: https://github.com/hhatto/autopep8/blob/main/README.rst How to run test cases directly. ```bash python test/test_autopep8.py ``` -------------------------------- ### fix_e231() Example Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/fix-methods-reference.md Adds space after commas in lists, tuples, function calls. ```python def fix_e231(self, result) -> Optional[List[int]] # Before data = [1,2,3,4] # After data = [1, 2, 3, 4] ``` -------------------------------- ### Programmatic Configuration Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/README.md Shows how to configure autopep8 programmatically using dictionaries or command-line arguments. ```python import autopep8 # Create options from dict options = { 'aggressive': 1, 'max_line_length': 100, 'ignore': ['E226', 'E24'], } fixed = autopep8.fix_code(source, options=options) # Or parse command-line style arguments options = autopep8.parse_args([ '--aggressive', '--max-line-length', '100', '--ignore', 'E226,E24', 'dummy.py' ]) ``` -------------------------------- ### E121-E129, E131 - Continuation line indentation issues Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/errors.md Example of continuation line indentation. ```python # Before (E121) result = some_function(argument1, argument2, argument3, argument4) # After result = some_function(argument1, argument2, argument3, argument4) ``` -------------------------------- ### Command-Line Usage Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/README.md Demonstrates various command-line options for autopep8. ```bash # Basic fix (output to stdout) autopep8 myfile.py # In-place modification autopep8 --in-place myfile.py # Show diff autopep8 --diff myfile.py # Aggressive fixes autopep8 --aggressive --aggressive myfile.py # Fix only specific errors autopep8 --select=E1,E3 myfile.py # Recursively fix directory autopep8 --in-place --recursive src/ ``` -------------------------------- ### E221-E228, E241-E242 - Operator and keyword whitespace Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/errors.md Example of whitespace normalization around operators and keywords. ```python # Before x=1+2 y = 3 z = 4 # After x = 1 + 2 y = 3 z = 4 ``` -------------------------------- ### Configuration Defaults Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/utility-functions.md Defines the default paths and filenames for configuration files used by autopep8. ```python DEFAULT_CONFIG = os.path.expanduser('~/.config/pycodestyle') # Global config path PROJECT_CONFIG = ('setup.cfg', 'tox.ini', '.pep8', '.flake8') # Config file names ``` -------------------------------- ### check_syntax() Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/utility-functions.md Verifies that source code is syntactically valid Python. ```python def check_syntax(code: str) -> bool ``` ```python import autopep8 code = "x = 1" if autopep8.check_syntax(code): print("Valid Python") else: print("Syntax error") ``` -------------------------------- ### fix_e112() / fix_e113() / fix_e116() Example Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/fix-methods-reference.md Fixes under-indented or over-indented lines by adding or removing spaces. ```python def fix_e112(self, result) -> Optional[List[int]] # Before (E112 - expected indented block) if True: x = 1 # Not indented # After if True: x = 1 ``` -------------------------------- ### fix_e121() through fix_e129(), fix_e131() Example Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/fix-methods-reference.md Reindents continuation lines to match opening bracket or hanging indent. ```python def fix_e121(self, result) -> Optional[List[int]] # Before (E122) result = some_func(arg1, arg2, arg3) # After result = some_func(arg1, arg2, arg3) ``` -------------------------------- ### Use autopep8 as a module - fix_code() Source: https://github.com/hhatto/autopep8/blob/main/README.rst Shows the simplest way to use autopep8 as a module via the fix_code() function. ```python >>> import autopep8 >>> autopep8.fix_code('x= 123\n') 'x = 123\n' ``` -------------------------------- ### Batch Process Multiple Files Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/README.md Demonstrates how to process multiple Python files in place using autopep8. ```python import autopep8 files = ['file1.py', 'file2.py', 'file3.py'] options = autopep8.parse_args(['--in-place', '--jobs', '4'] + files) results = autopep8.fix_multiple_files(files, options) ``` -------------------------------- ### Use autopep8 as a module - fix_code() with options Source: https://github.com/hhatto/autopep8/blob/main/README.rst Demonstrates using fix_code() with options. ```python >>> import autopep8 >>> autopep8.fix_code('print( 123 )\n', ... options={'ignore': ['E']}) 'print( 123 )\n' ``` -------------------------------- ### Reindenter class constructor and run method Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/api-reference.md Reindents Python code to use consistent indentation. Handles complex cases like hanging comments and multiline strings. The run method reindents the code and returns the result. ```python import autopep8 messy = """ def foo(): \t\tx = 1 y = 2 """ reindenter = autopep8.Reindenter(messy, leave_tabs=False) clean = reindenter.run(indent_size=4) print(clean) ``` -------------------------------- ### Case 1: Format Python Code to PEP 8 Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/README.md Formats Python code to PEP 8 using default whitespace-only fixes. ```python import autopep8 code = """ import sys, os def foo( ): x=1 return x """ # Use defaults (whitespace-only fixes) fixed = autopep8.fix_code(code) ``` -------------------------------- ### find_files() Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/utility-functions.md Recursively finds Python files matching criteria. ```python def find_files(filenames: list[str], recursive: bool, exclude: str) -> generator[str] ``` ```python import autopep8 files = list(autopep8.find_files( ['src/'], recursive=True, exclude='__pycache__,.venv,*_test.py' )) ``` -------------------------------- ### Line length exceeding maximum Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/errors.md Provides an example of fixing E501 by breaking a long line at operators, brackets, or strings. ```python # Before (>79 chars) result = some_very_long_function_name(argument1, argument2, argument3, argument4) # After result = some_very_long_function_name( argument1, argument2, argument3, argument4) ``` -------------------------------- ### Pre-commit Configuration Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/README.md Configuration for using autopep8 with pre-commit. ```yaml repos: - repo: https://github.com/hhatto/autopep8 rev: v2.0.0 hooks: - id: autopep8 args: ['--in-place', '--aggressive', '--aggressive'] ``` -------------------------------- ### Show Diff Without Modifying Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/README.md Shows how to view the changes autopep8 would make to a file without actually modifying it, by displaying a unified diff. ```python import autopep8 import sys options = autopep8.parse_args(['--diff', 'myfile.py']) result = autopep8.fix_file('myfile.py', options=options) print(result) # Prints unified diff ``` -------------------------------- ### match_file() Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/utility-functions.md Checks if a file matches exclude patterns. ```python def match_file(filename: str, exclude: str) -> bool ``` ```python import autopep8 exclude = ".git,__pycache__,.venv,*_test.py" print(autopep8.match_file('test_module.py', exclude)) # True (excluded) print(autopep8.match_file('module.py', exclude)) # False (included) print(autopep8.match_file('.venv/lib/module.py', exclude)) # True (excluded) ``` -------------------------------- ### LineEndingWrapper Constructor Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/api-reference.md Wrapper for output streams that normalizes line endings to the target format (LF, CRLF, or CR). ```python class LineEndingWrapper(object) ``` ```python def __init__(self, output, newline='\n') ``` -------------------------------- ### Exclude Certain Patterns Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/README.md Example of configuring autopep8 to exclude specific files or directories (like test files, __pycache__, or venv) during recursive processing. ```python import autopep8 # Skip test files and __pycache__ options = autopep8.parse_args([ '--in-place', '--recursive', '--exclude', '*_test.py,__pycache__,venv', 'src/' ]) ``` -------------------------------- ### docstring_summary() Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/utility-functions.md Extracts the first line of a docstring (used for help text). ```python def docstring_summary(docstring: str) -> str ``` ```python import autopep8 doc = """Fix indentation issues. This function handles various indentation problems. """ summary = autopep8.docstring_summary(doc) print(summary) # 'Fix indentation issues.' ``` -------------------------------- ### Regex Patterns Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/utility-functions.md Provides regular expression patterns used for various code analysis tasks within autopep8. ```python PYTHON_SHEBANG_REGEX = re.compile(r'^#!.*\bpython[23]?\b\s*$') LAMBDA_REGEX = re.compile(r'([\w.]+)\s=\slambda\s*([)(=\w,\s.]*):') COMPARE_NEGATIVE_REGEX = re.compile(r'\b(not)\s+([^][)(}{]+?)\s+(in|is)\s') # ... and others for code analysis ``` -------------------------------- ### generate_tokens() Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/utility-functions.md Convenience reference to the CachedTokenizer's generate_tokens method. It caches tokenization results. ```python generate_tokens = _cached_tokenizer.generate_tokens ``` ```python import autopep8 code = "x = 1" tokens = autopep8.generate_tokens(code) for token in tokens: print(token) ``` -------------------------------- ### Configuration Dictionary Structure Source: https://github.com/hhatto/autopep8/blob/main/_autodocs/types.md Structure of the configuration dictionary used when interacting with the programmatic API of autopep8. ```python { 'aggressive': int or None, 'max_line_length': int or None, 'ignore': list[str] or None, 'select': list[str] or None, 'indent_size': int or None, 'hang_closing': bool or None, # ... other options } ```