Git, Clean Code & Docs

๐Ÿ Python 3.12+ ๐ŸŸข Chapter 64 of 65 ๐Ÿ“‚ Phase 12: Automation and Professional Skills ๐Ÿ“… 2026 Edition
๐Ÿ“Œ Covered in this chapter: Git Version Control Workflow ยท PEP 8 Style Guide ยท Formatting with Black & Ruff ยท Docstrings (Google/NumPy Style) ยท SOLID Principles
Master professional software engineering standards in Python: Git branch and pull-request workflows, adhering to the PEP 8 style guide, automated formatting with Black and Ruff, writing documentation with Google-style docstrings, and applying the SOLID design principles.
1Professional Git Version Control Workflow

Git is the universal distributed version control system used by software engineering teams across the globe.

The Standard Feature Branch Git Workflow:

  1. git checkout -b feature/user-authentication: Create and switch to a dedicated feature branch.
  2. git add .: Stage modified and newly created files.
  3. git commit -m "feat(auth): implement JWT token login": Commit changes with an informative Conventional Commit message.
  4. git push origin feature/user-authentication: Push branch to GitHub/GitLab.
  5. Open a Pull Request (PR) for peer code review and automated CI/CD testing before merging into main!
๐Ÿ’ป Reference: Essential Professional Git Commands
# Git Command Reference Summary:
git_commands = {
    "git status":           "Inspect staged, unstaged, and untracked file changes",
    "git diff":             "View exact line-by-line diff of unstaged modifications",
    "git log --oneline -n 5":"Display concise history of the last 5 commits",
    "git branch -a":        "List all local and remote tracking branches",
    "git stash":            "Temporarily shelve uncommitted local changes without losing work"
}

print("--- ๐Ÿ› ๏ธ Core Professional Git Commands ---")
for cmd, desc in git_commands.items():
    print(f"โ€ข {cmd:25}: {desc}")
๐Ÿ” What is a .gitignore file?

Always include a .gitignore file at project root to prevent checking in virtual environments (venv/), compiled bytecode (__pycache__/), OS artifacts (.DS_Store), and secret files (.env).

2Clean Code, PEP 8 Formatting & Google-Style Docstrings

Code is read far more often than it is written. Writing clean, readable code is a core trait of senior software engineers.

The 4 Essential Clean Code Principles:

  • DRY (Don't Repeat Yourself): Consolidate duplicated logic into reusable functions.
  • KISS (Keep It Simple, Stupid): Choose straightforward, transparent solutions over clever, obfuscated code.
  • SOLID Principles: Single Responsibility (a function or class should do exactly one thing well).
  • Automated Formatting (Black / Ruff): Use black . to automatically format code according to PEP 8 standards with zero arguments.
๐Ÿ’ป Example 2: Clean Code with Type Hints and Google-Style Docstring
def calculate_employee_bonus(base_salary: float, performance_rating: float, years_at_company: int) -> float:
    """Calculates annual performance bonus with tenure multiplier.

    Adheres to Google Docstring Style standards.

    Args:
        base_salary (float): The annual base salary in INR.
        performance_rating (float): Performance score from 1.0 (lowest) to 5.0 (highest).
        years_at_company (int): Number of completed full years at the organization.

    Returns:
        float: Total bonus amount in INR rounded to 2 decimal places.

    Raises:
        ValueError: If performance_rating is outside the 1.0 to 5.0 range.
    """
    if not (1.0 <= performance_rating <= 5.0):
        raise ValueError("performance_rating must be between 1.0 and 5.0")

    # Base bonus percentage:
    bonus_percentage = (performance_rating / 5.0) * 0.15 # Up to 15%
    
    # Seniority loyalty multiplier (+1% per year up to 5%):
    loyalty_bonus = min(years_at_company * 0.01, 0.05)
    
    total_bonus = base_salary * (bonus_percentage + loyalty_bonus)
    return round(total_bonus, 2)

# Calculate bonus:
bonus = calculate_employee_bonus(base_salary=1200000.0, performance_rating=4.8, years_at_company=3)
print(f"Computed Annual Bonus: โ‚น{bonus:,.2f}")
๐Ÿ” Type Hints & Docstring Inspection:

Combining PEP 484 type annotations (base_salary: float) with structured docstrings allows documentation generators (like Sphinx / MkDocs) to build interactive API documentation websites automatically.

โš ๏ธ Common Developer Pitfall: Using Meaningless Variable Names (x, temp, data2, a1)

Variables with names like "temp" or "data2" obscure business intent. Always use descriptive, intent-revealing names: "active_user_count", "monthly_revenue", "is_account_verified".

๐Ÿ’ป Hands-on Interactive Practice Challenge

Refactor messy code: Write a clean function is_eligible_for_loan(credit_score, income, existing_debt) with type hints and boolean expression.

Python 3 Practice Challenge โ–ถ Run in Compiler
def is_eligible_for_loan(credit_score: int, annual_income: float, current_debt: float) -> bool:
    debt_to_income_ratio = current_debt / annual_income if annual_income > 0 else 1.0
    return credit_score >= 700 and debt_to_income_ratio <= 0.40

print("Candidate 1 Eligible:", is_eligible_for_loan(750, 1200000, 300000)) # True
print("Candidate 2 Eligible:", is_eligible_for_loan(620, 1500000, 200000)) # False (Low score)
Run This Challenge in Online Python IDE โ†’
โ“ Frequently Asked Questions (FAQ)

Q What is Ruff in the Python ecosystem?

Ruff is an extremely fast Python linter and formatter written in Rust that replaces Flake8, isort, Black, and pydocstyle while running 10-100x faster.

Q What is the difference between git merge and git rebase?

git merge combines branches by creating a new merge commit preserving full branch history. git rebase replays your commits on top of the target branch, creating a clean linear commit history.

Q What is a pre-commit hook in Git?

A pre-commit hook is an automated script that runs linters and formatters (like Black and Ruff) before every commit, automatically rejecting commits that violate style guidelines.

OC
Written by Our Compiler Technical Editorial Team
Reviewed for accuracy & tested on Python 3.12+ runtime ยท Last updated August 2026