// Follows Pythonic patterns and avoids common Python pitfalls
# Python Best Practices
Write clean, Pythonic code that follows community standards.
## Use List Comprehensions
```python
# Bad
squares = []
for x in range(10):
squares.append(x**2)
# Good
squares = [x**2 for x in range(10)]
# Bad
even_numbers = []
for x in numbers:
if x % 2 == 0:
even_numbers.append(x)
# Good
even_numbers = [x for x in numbers if x % 2 == 0]
```
## Use Context Managers
```python
# Bad
f = open('file.txt')
data = f.read()
f.close()
# Good
with open('file.txt') as f:
data = f.read()
# Multiple resources
with open('input.txt') as infile, open('output.txt', 'w') as outfile:
outfile.write(infile.read())
```
## Avoid Mutable Default Arguments
```python
# Bad - shared state bug
def add_item(item, items=[]):
items.append(item)
return items
# Good
def add_item(item, items=None):
if items is None:
items = []
items.append(item)
return items
```
## Use Generators for Large Datasets
```python
# Bad - loads everything in memory
def get_numbers():
return [i for i in range(1000000)]
# Good - yields one at a time
def get_numbers():
for i in range(1000000):
yield i
# Usage
for num in get_numbers():
process(num)
```
## Use enumerate() Instead of range(len())
```python
# Bad
for i in range(len(items)):
print(i, items[i])
# Good
for i, item in enumerate(items):
print(i, item)
```
## Use zip() for Parallel Iteration
```python
# Bad
for i in range(len(names)):
print(names[i], ages[i])
# Good
for name, age in zip(names, ages):
print(name, age)
```
## Use f-strings for Formatting
```python
name = "Alice"
age = 30
# Bad
print("My name is " + name + " and I'm " + str(age))
print("My name is %s and I'm %d" % (name, age))
# Good
print(f"My name is {name} and I'm {age}")
print(f"Calculation: {2 + 2}")
```
## Use Type Hints
```python
# Good
def greet(name: str) -> str:
return f"Hello, {name}"
def add(a: int, b: int) -> int:
return a + b
from typing import List, Dict, Optional
def process_items(items: List[str]) -> Dict[str, int]:
return {item: len(item) for item in items}
def find_user(user_id: int) -> Optional[dict]:
# Returns dict or None
pass
```
## Use Pathlib for File Paths
```python
# Bad
import os
path = os.path.join('folder', 'subfolder', 'file.txt')
if os.path.exists(path):
with open(path) as f:
data = f.read()
# Good
from pathlib import Path
path = Path('folder') / 'subfolder' / 'file.txt'
if path.exists():
data = path.read_text()
```
## Use dataclasses for Data Containers
```python
# Bad
class Person:
def __init__(self, name, age, email):
self.name = name
self.age = age
self.email = email
def __repr__(self):
return f"Person({self.name}, {self.age}, {self.email})"
# Good
from dataclasses import dataclass
@dataclass
class Person:
name: str
age: int
email: str
```
## Use Virtual Environments
```bash
# Create virtual environment
python -m venv venv
# Activate (Unix)
source venv/bin/activate
# Activate (Windows)
venv\Scripts\activate
# Install dependencies
pip install -r requirements.txt
```
## Follow PEP 8 Style Guide
```python
# Bad
def MyFunction(someVariable):
result=someVariable*2
return result
# Good
def my_function(some_variable):
result = some_variable * 2
return result
```
## Use is for None Comparison
```python
# Bad
if value == None:
pass
# Good
if value is None:
pass
# Bad
if not value == None:
pass
# Good
if value is not None:
pass
```
## Avoid Using * Imports
```python
# Bad
from module import *
# Good
from module import specific_function, SpecificClass
# or
import module
```
These practices make Python code more readable, maintainable, and Pythonic.6 matches