Python is known for its “elegance”, “simplicity”, and “readability”, and one of the keys to achieving these characteristics is good coding standards and clear type annotations. As project scales increase and team members grow, writing Python code that is “understandable and modifiable” becomes more important than just writing “working code”.
This article will take you deep into two core themes: the first is Type Hinting, which helps make code clearer and more maintainable; the second is PEP 8 coding standards, which makes your code more aligned with the best practices of the Python community.
1. Why Type Annotations are Needed
Python is a dynamically typed language, where variable types are determined at runtime:
a = 10
a = "Hello"
This flexibility brings convenience, but it can also lead to errors in large projects. For example, when the types of function parameters or return values are unclear, maintainers may find it difficult to understand the function’s behavior:
def add(x, y):
return x + y
<span>add(3, 5)</span> can execute, but <span>add("3", "5")</span> can also run (performing string concatenation), which may not be the expected result.
2. Basic Syntax of Type Annotations
Starting from Python 3.5, type annotations (Type Hints) were introduced, allowing type specifications to be added to variables, parameters, and return values, thereby enhancing readability and maintainability.
def add(x: int, y: int) -> int:
return x + y
This indicates:
- •
<span>x</span>and<span>y</span>should be integers; - • The function returns an integer.
Although the Python interpreter does not enforce type checking, editors (like VSCode, PyCharm) or static analysis tools (like mypy) can detect type issues before compilation.
1. Variable Annotations
name: str = "Python"
age: int = 25
price: float = 99.9
is_valid: bool = True
Type annotations do not change the essence of the variable; they merely add type information.
2. Complex Type Annotations
The <span>typing</span> module in Python provides a rich set of tools for type annotations:
from typing import List, Tuple, Dict, Optional
- • List: List type
numbers: List[int] = [1, 2, 3] - • Tuple: Tuple type
point: Tuple[int, int] = (10, 20) - • Dict: Dictionary type
user: Dict[str, int] = {"age": 18} - • Optional: Optional type
name: Optional[str] = None
3. Function Type Annotation Examples
from typing import List
def average(scores: List[int]) -> float:
return sum(scores) / len(scores)
More complex example:
from typing import Dict, List, Union
def process_data(data: Dict[str, Union[int, List[int]]]) -> None:
print("Processing data:", data)
4. Type Annotations in Classes and Methods
In object-oriented programming, type annotations are also applicable:
class User:
def __init__(self, name: str, age: int):
self.name = name
self.age = age
def greet(self) -> str:
return f"Hello, I am {self.name}, {self.age} years old"
5. Type Checking Tool: mypy
Install <span>mypy</span>:
pip install mypy
Check code types:
mypy example.py
Example:
def greet(name: str) -> str:
return 123 # Error: return type mismatch
Running mypy will prompt:
error: Incompatible return value type (got "int", expected "str")
In this way, you can discover potential errors in advance and improve code quality.
3. PEP 8 — The Official Python Style Guide
PEP 8 (Python Enhancement Proposal 8) is the officially recommended coding style standard, which defines a unified specification for Python coding, making team collaboration more efficient and code more readable.
1. Naming Conventions
| Type | Example | Description |
| Module Name | <span>math_utils</span> |
All lowercase, separated by underscores |
| Class Name | <span>UserProfile</span> |
Use CamelCase (PascalCase) |
| Function Name | <span>get_user_info</span> |
All lowercase, separated by underscores |
| Variable Name | <span>total_count</span> |
Short and meaningful |
| Constant Name | <span>MAX_RETRY</span> |
All uppercase |
2. Indentation and Spaces
- • Each level of indentation uses 4 spaces;
- • Leave one space on both sides of operators;
- • Leave one space after commas.
Example:
def add(a, b):
return a + b
if a == b:
print("Equal")
Do not write like this:
if a==b:print("Equal")
3. Blank Lines and Function Layout
- • Two blank lines between top-level functions and classes;
- • One blank line between methods in a class;
- • Use blank lines reasonably to improve readability.
4. Import Standards
- • Import order: Standard library → Third-party libraries → Local modules;
- • Each import should occupy one line.
Example:
import os
import sys
import requests
from myproject.utils import helper
5. Line Width and Comments
- • Each line should not exceed 79 characters;
- • Comments should be concise and accurate;
- • Docstrings should use triple quotes
<span>"""</span>.
Example:
def greet(name: str) -> str:
"""Return a simple greeting"""
return f"Hello, {name}"
4. Using Automation Tools to Enhance Code Standards
You can use the following tools to automatically check or fix code style:
- • flake8: Check if the code complies with PEP 8
pip install flake8 flake8 your_code.py - • black: Automatically format code
pip install black black your_code.py - • isort: Automatically sort import statements
pip install isort isort your_code.py
These tools, combined with type checking (mypy), can keep your code clean and professional.
5. Conclusion
Type annotations and PEP 8 are essential cornerstones for writing high-quality Python code. They not only make the code more standardized and readable but also provide a solid foundation for collaboration and maintenance in large projects.
Key Points Recap:
| Content | Description |
| Type Annotations | Clarify variable and function types, improving readability and safety |
| typing Module | Provides tools like List, Dict, Tuple, Union, Optional |
| mypy | Static type checker to discover potential errors early |
| PEP 8 | Official Python coding standards to enhance code cleanliness |
| flake8 / black / isort | Automation tools to enforce standards |