-
Notifications
You must be signed in to change notification settings - Fork 0
Code Style
Dragon edited this page Dec 23, 2025
·
2 revisions
Last updated: 12/22/2025
┌─────────────────────────────────────────────┐
│ Code Style Checklist │
├─────────────────────────────────────────────┤
│ ✅ PEP 8 compliant │
│ ✅ Clear, descriptive names │
│ ✅ Comprehensive docstrings │
│ ✅ Type hints (optional but recommended) │
│ ✅ Consistent error handling │
│ ✅ Modular, single-responsibility design │
│ ✅ Test-driven approach │
└─────────────────────────────────────────────┘
-
Snake case:
search_manager.py,browser_state.py - Descriptive: Clearly indicate purpose
- Short but meaningful: Avoid abbreviations
# Variables & functions: snake_case
search_results = []
def parse_html_content(): ...
# Constants: UPPER_SNAKE_CASE
MAX_RESULTS = 10
DEFAULT_ENGINE = "brave"
# Classes: PascalCase
class SearchManager: ...
class BrowserState: ...
# Private: _leading_underscore
def _internal_helper(): ..."""
Module docstring - What this module does
"""
# 1. Standard library imports
import json
import re
import time
from typing import List, Dict, Optional
# 2. Third-party imports
import requests
from colorama import Fore
# 3. Constants
MAX_RESULTS = 10
TIMEOUT = 10
# 4. Classes
class MainClass:
"""Class docstring"""
pass
# 5. Functions
def helper_function():
"""Function docstring"""
pass
# 6. Main guard
if __name__ == "__main__":
pass- Standard library
- Third-party packages
- Local modules (if we had them)
"""
Search Manager Module
Handles web search across multiple engines, parsing results,
and implementing fallback strategies.
"""
class SearchManager:
"""
Main search manager class.
Attributes:
state (BrowserState): Current browser state
network (NetworkManager): Network handler
"""def search(self, query, engine=None):
"""
Search the web for a query.
Args:
query (str): Search query
engine (str, optional): Engine to use
Returns:
List[dict]: Search results
Raises:
SearchError: If search fails
NetworkError: If connection fails
Examples:
>>> search("python tutorial")
[{'title': 'Python Tutorial', ...}]
"""# ✅ Good spacing
def function_name(arg1, arg2=default):
result = []
for item in items:
if condition:
result.append(item)
return result
# ❌ Avoid
def badFunction(arg1,arg2=default):
result=[]
for item in items:
if condition:result.append(item)
return result- Max 79 characters per line
- Break long lines at logical points
- Use parentheses for continued lines
class NaviDuckError(Exception):
"""Base exception."""
class SearchError(NaviDuckError):
"""Search-related errors."""
class NetworkError(NaviDuckError):
"""Network-related errors."""def handle_error(self, error):
if isinstance(error, NetworkError):
print(f"{Colors.ERROR}❌ Network error. Check connection.{Colors.RESET}")
print(f"{Colors.INFO}Try: 1. Check internet 2. Use Tor{Colors.RESET}")# tests/test_search_manager.py
import pytest
class TestSearchManager:
def setup_method(self):
"""Setup before each test."""
self.manager = SearchManager()
def test_valid_search(self):
"""Test search with valid query."""
results = self.manager.search("test")
assert len(results) > 0
@pytest.mark.parametrize("engine", ["brave", "ddg", "google"])
def test_engine_parsing(self, engine):
"""Test different search engines."""
results = self.manager.search("test", engine=engine)
assert isinstance(results, list)<type>[optional scope]: <description>
[optional body]
[optional footer]
-
feat:New feature -
fix:Bug fix -
docs:Documentation -
style:Formatting -
refactor:Code refactoring -
test:Tests -
chore:Maintenance
git commit -m "feat: add Brave search engine"
git commit -m "fix: correct CAPTCHA detection logic"
git commit -m "docs: update search guide"# ❌ Vague names
x = get_data()
a = process(x)
# ❌ Magic numbers
time.sleep(5) # What does 5 mean?
# ❌ Overly complex one-liners
result = [x for x in data if x > 0 and x < 100 and x % 2 == 0]
# ❌ Ignoring errors
try:
do_something()
except:
pass # Silent failure!# ✅ Clear names
search_results = fetch_search_results()
processed_results = filter_valid_results(search_results)
# ✅ Named constants
SEARCH_TIMEOUT = 5
time.sleep(SEARCH_TIMEOUT)
# ✅ Clear, readable logic
valid_results = [
result for result in data
if 0 < result < 100 and result % 2 == 0
]
# ✅ Proper error handling
try:
do_something()
except SpecificError as e:
logger.error(f"Operation failed: {e}")
handle_error_gracefully()- Code follows PEP 8
- Descriptive variable/function names
- Comprehensive docstrings
- Error handling implemented
- Tests written and passing
- No commented-out debug code
- Documentation updated
- Commit message follows conventions
- Single responsibility per function/class
- No duplicated code
- Clear and maintainable
- Edge cases handled
- Performance considered
- Security implications reviewed
# Install tools
pip install black flake8 mypy
# Format code
black naviduck.py
# Check style
flake8 naviduck.py
# Type checking (optional)
mypy naviduck.py// .vscode/settings.json
{
"python.formatting.provider": "black",
"python.linting.enabled": true,
"python.linting.flake8Enabled": true,
"python.linting.mypyEnabled": true
}- Test Coverage: > 80%
- Code Complexity: Cyclomatic complexity < 10
- Documentation: 100% of public APIs documented
- Duplication: < 3% duplicated code
- Maintainability: A rating on CodeClimate
- Be Clear: Write code for the next developer
- Be Consistent: Follow existing patterns
- Be Complete: Document and test thoroughly
- Be Considerate: Handle errors gracefully
- Be Clean: Keep it simple and maintainable
Last updated: 12/22/2025
Code Style Summary version: 2.0
Remember: Good code is like a good joke - it needs no explanation, but documentation helps! 😄