Coding Best Practices
Indentation Best Practices
Consistent Spacing
Always use 4 spaces for indentation. Avoid mixing tabs and spaces.
## Correct Indentation
def example_function():
if True:
print("Properly indented code")
for item in range(5):
print(item)
Recommended Indentation Strategies
Practice |
Description |
Recommendation |
Space Size |
Indentation width |
Use 4 spaces consistently |
Alignment |
Block-level spacing |
Maintain uniform indentation |
IDE Configuration |
Editor settings |
Configure auto-indent |
Automated Indentation Management
graph TD
A[Indentation Management] --> B[Tools]
B --> C[IDE Configurations]
B --> D[Linters]
B --> E[Code Formatters]
- Black: Automatic Python code formatter
- pylint: Static code analysis tool
- autopep8: Automatic PEP 8 code formatter
Configuration Example
## .pylintrc configuration
[MASTER]
## Use 4 spaces for indentation
indent-string=' '
## Enforce consistent indentation
indent-after-paren=4
Common Pitfalls to Avoid
- Mixing tabs and spaces
- Inconsistent indentation within a project
- Manually adjusting indentation
IDE Configuration Tips
Visual Studio Code
{
"python.formatting.provider": "black",
"editor.insertSpaces": true,
"editor.tabSize": 4
}
Automated Checking
Use pre-commit hooks to enforce indentation standards:
#!/bin/bash
## pre-commit hook for indentation
black --check .
pylint **/*.py
Proper indentation:
- Improves code readability
- Reduces potential errors
- Enhances collaboration
LabEx Recommendation
At LabEx, we emphasize:
- Consistent 4-space indentation
- Automated formatting
- Regular code reviews
Advanced Techniques
Contextual Indentation
## Using context managers for clean indentation
with open('file.txt', 'r') as file:
content = file.read()
## Automatically handles file closing
Final Checklist
By following these best practices, you'll write more maintainable and professional Python code.