How to Format Your Code in Python: A Comprehensive Guide
By hientd, at: 2024年1月3日22:23
How to Format Your Code in Python: A Comprehensive Guide
1. Definition of PEP8 Formatting in Python
PEP 8 is the official style guide for Python code. It was written to promote a common coding style that improves the readability and consistency of Python code. Key elements of PEP 8 include:
- Indentation: Use 4 spaces per indentation level.
- Line Length: Limit lines to a maximum of 79 characters.
- Blank Lines: Separate top-level function and class definitions with two blank lines.
- Imports: Group imports into standard library, third-party, and local imports.
- Whitespace: Avoid extraneous whitespace in expressions and statements.
Following these guidelines ensures your code is clean, readable, and maintainable.
2. Examples of Bad Code
Here are some examples of poorly formatted code:
############ Example 1: Inconsistent indentation and spacing
def example1():
a=5
b = 10
if a < b:
print("a is less than b")
else:
print( "a is not less than b")
############ Example 2: Poor naming conventions and lack of comments
def calc(x, y):
return x+y
def mul(X,Y):
return X*Y
a = 10
b = 20
result1 = calc(a,b)
result2 = mul(a, b)
print(result1)
print(result2)
############ Example 3: Misuse of spacing and lack of comments
def greet (name ):
print( "Hello, " + name)
greet( "Alice" )
# Example 4: Improper use of line breaks
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
print(factorial(5))
############ Example 5: Inconsistent naming conventions and spacing
def ConvertTemp(celsius):
Farenheit = celsius * 9/5 + 32
return Farenheit
print(ConvertTemp(30))
############ Example 6: Lack of proper error handling and formatting
def divide(a, b):
return a / b
print(divide(10, 0))
3. Using flake8
to Check Code Issues and black
to Re-format
Using flake8
flake8
is a tool for checking the style and quality of Python code. It combines PyFlakes, pycodestyle, and McCabe.
To install flake8
:
pip install flake8
To check your code:
flake8 your_script.py
Using black
black
is an uncompromising Python code formatter. It reformats entire files in place.
To install black
:
pip install black
To reformat your code:
black your_script.py
4. Using isort
and bandit
for Better Code Formatting and Security
Using isort
isort
is a Python utility for sorting imports.
To install isort
:
pip install isort
To sort imports in your code:
isort your_script.py
Using bandit
bandit
is a tool designed to find common security issues in Python code.
To install bandit
:
pip install bandit
To run a security check:
bandit -r your_script.py
5. Using pre-commit
for Auto Formatting on Every Git Commit
pre-commit
is a framework for managing and maintaining multi-language pre-commit hooks.
Installing pre-commit
To install pre-commit
:
pip install pre-commit
Setting Up pre-commit
Create a .pre-commit-config.yaml
file in your repository with the following content:
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v3.4.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- repo: https://github.com/psf/black
rev: 23.3.0
hooks:
- id: black
- repo: https://github.com/timothycrosley/isort
rev: 5.10.1
hooks:
- id: isort
Install the pre-commit hooks:
pre-commit install
Now, the configured hooks will run automatically on every git commit
.
Conclusion
Maintaining a consistent coding style in Python is essential for readability and collaboration. By following PEP8 guidelines, using tools like flake8
, black
, isort
, and bandit
, and integrating pre-commit
for automated checks, you can ensure your code is clean, secure, and well-formatted. Start incorporating these practices into your workflow to improve the quality and maintainability of your Python projects.