PEP 8 is Python's coding style guide. Following it improves code readability and consistency. Use 4 spaces for indentation and keep each line under 79 characters.
Python 3.5+ supports type hints. Using type annotations makes code clearer and helps IDEs provide better intelligent suggestions.
def greet(name: str) -> str:
return f"Hello, {name}!"
List comprehensions are concise and efficient, but excessive complexity reduces readability. Keep them simple and clear.
# Good practice
squares = [x**2 for x in range(10)]
# Avoid
result = [(x, y, x*y) for x in range(10) if x % 2 == 0 for y in range(5) if y > 2]
Use the with statement to automatically manage the opening and closing of files or other resources.
with open('file.txt', 'r') as f:
content = f.read()
Mutable objects as default arguments can lead to unexpected behavior.
# Avoid
def add_item(item, items=[]):
items.append(item)
return items
# Recommended
def add_item(item, items=None):
if items is None:
items = []
items.append(item)
return items
Create independent virtual environments for each project to manage dependencies and avoid version conflicts.
Write clear docstrings for functions, classes, and modules to describe their purpose, parameters, and return values.
Python 3.6+ recommends using f-strings, which are faster and more readable than % formatting and .format().
name = "Alice"
print(f"Hello, {name}!")
Catch specific exception types, avoid bare except clauses, and ensure error information is traceable.