Skip to content

Latest commit

Β 

History

History
686 lines (455 loc) Β· 12.6 KB

File metadata and controls

686 lines (455 loc) Β· 12.6 KB

PEP 1 explains what PEPs are and how they work.

PEP 8 was written by Guido van Rossum (Python’s creator) and others, and became the canonical style guide.

Other famous PEPs:

PEP 20 β†’ The Zen of Python (import this)

PEP 484 β†’ Type hints

PEP 572 β†’ The walrus operator (:=)


🐍 Python Coding Standards & PEP 8 Cheat Sheet (2025 Edition)

A practical, modern guide to writing clean, professional Python code.
Covers PEP 8, industry standards (2025), and rare pitfalls every dev should know.


πŸ“Œ 1. Indentation & Line Length

  • Use 4 spaces per indentation level (never tabs).
  • Max line length: 88 chars (modern consensus, e.g., black formatter).
def my_function():
    for i in range(5):
        print(i)  # βœ… Clean indentation

πŸ“Œ 2. Blank Lines

  • 2 blank lines before top-level functions/classes.
  • 1 blank line between methods in a class.
class MyClass:
    def method_one(self):
        pass

    def method_two(self):
        pass

πŸ“Œ 3. Imports

  • One import per line.
  • Order: standard library β†’ third-party β†’ local.
  • Use absolute imports, relative only inside packages.
  • Avoid wildcard imports.
import os
import sys

import requests

from myproject import utils

πŸ“Œ 4. Naming Conventions

  • Variables / functions β†’ lower_case_with_underscores
  • Classes β†’ CapWords
  • Constants β†’ UPPER_CASE_WITH_UNDERSCORES
  • Private/internal β†’ _leading_underscore
MAX_SIZE = 100

def calculate_area(radius):
    return 3.14 * radius * radius

class Circle:
    def __init__(self, radius):
        self._radius = radius

πŸ“Œ 5. Spacing Rules

βœ… Correct vs ❌ Wrong

x = y + z        # βœ…
x=y+z            # ❌

func(a, b, c)    # βœ…
func(a , b , c ) # ❌

my_list = [1, 2, 3]  # βœ…
my_list = [ 1 ,2 , 3 ]  # ❌

πŸ“Œ 6. Docstrings & Comments

  • Use """triple quotes""" for docstrings.
  • First line = short summary.
  • Comments explain why, not what.
def add(x: int, y: int) -> int:
    """Return the sum of x and y."""
    return x + y

πŸ“Œ 7. Function & Class Definitions

  • Break long arg lists after (.
def my_function(param1, param2,
                param3, param4):
    pass

πŸ“Œ 8. Boolean Checks

  • Don’t compare to True / False.
if my_list:          # βœ…
if len(my_list) != 0: # βœ…
if my_list == True:  # ❌

πŸ“Œ 9. Whitespace Pitfalls

if x == 4: print(x, y)  # βœ…
if x == 4 : print(x , y )  # ❌

πŸ“Œ 10. General Principles

  • Readability > Cleverness.
  • Consistency matters.
  • Follow The Zen of Python (import this).

πŸ“Œ 11. Code Layout

  • Don’t align variables artificially.
x = 1
y = 2
long_variable_name = 3  # βœ…

πŸ“Œ 12. String Quotes

  • Choose 'single' or "double" consistently.
  • Use """triple""" for docstrings.

πŸ“Œ 13. Expressions & Statements

  • Don’t use unnecessary parentheses.
  • No semicolons.
  • No multiple statements per line.
if x and y:  # βœ…
if (x and y):  # ❌

πŸ“Œ 14. Trailing Commas

my_list = [
    1,
    2,
    3,
]

πŸ“Œ 15. Comparisons

  • Use is for None, == for values.
if foo is None:  # βœ…
if foo == None:  # ❌

πŸ“Œ 16. Programming Recommendations

  • Use is not instead of not ... is.
  • Use .startswith() / .endswith().
  • Prefer in for membership.
if name.startswith("Mr."):  # βœ…

πŸ“Œ 17. Type Hints (Modern Standard)

  • Always use type hints in new code.
def greet(name: str) -> str:
    return f"Hello {name}"

πŸ“Œ 18. Variable Annotations

count: int = 0

πŸ“Œ 19. f-Strings (2025 Standard)

  • Use f-strings, not format() or %.
name = "Alice"
print(f"Hello {name}!")  # βœ…

πŸ“Œ 20. Path Handling

  • Prefer pathlib over os.path.
from pathlib import Path

data_dir = Path("data")
print(data_dir.exists())

πŸ“Œ 21. Loops

  • Prefer enumerate() and zip() to manual indexing.
for i, value in enumerate(my_list):
    print(i, value)

πŸ“Œ 22. Context Managers

  • Always use with for file/connection handling.
with open("file.txt") as f:
    data = f.read()

πŸ“Œ 23. Dataclasses (Modern Standard)

  • Prefer @dataclass for simple data holders.
from dataclasses import dataclass

@dataclass
class Point:
    x: int
    y: int

πŸ“Œ 24. Tools & Linters

  • Use black for formatting.
  • Use ruff or flake8 for linting.
  • Use mypy for type checking.

πŸ“Œ 25. Rare Pitfalls & Gotchas

⚠️ These cause real-world bugs if ignored:

  • Mutable default args:

    def bad(x, items=[]):   # ❌ Dangerous!
        items.append(x)
        return items
    
    def good(x, items=None):  # βœ…
        if items is None:
            items = []
        items.append(x)
        return items
  • Late binding closures:

    funcs = [lambda: i for i in range(3)]
    print([f() for f in funcs])  # ❌ [2, 2, 2]
    
    funcs = [lambda i=i: i for i in range(3)]
    print([f() for f in funcs])  # βœ… [0, 1, 2]
  • Floating-point precision:

    0.1 + 0.2 == 0.3  # ❌ False
  • Chained mutable defaults (dict/set pitfalls).


πŸ“Œ 26. When in Doubt

  • Be consistent with the existing project.
  • Prioritize readability.
  • Automate checks with pre-commit hooks.

βœ… Final Thoughts

PEP 8 isn’t about perfection β€” it’s about consistency, clarity, and collaboration. In 2025, teams standardize with:

  • black (formatting)
  • ruff/flake8 (linting)
  • mypy (type safety)

Write Python that’s:

  • Readable
  • Predictable
  • Maintainable

🐍 Python PEPs Made Simple (2025 Edition)

PEP = Python Enhancement Proposal.
It’s like a β€œrulebook page” or β€œproposal” for Python

Some PEPs are rules for writing code (style).
Some are new features.
Some are about packaging/distribution.

This doc explains the most useful PEPs simply, with examples.


πŸ“Œ PEP 8 – Style Guide for Python Code

The grammar rules for Python code.

βœ… Example:

def add(x: int, y: int) -> int:
    return x + y

❌ Example:

def add(x,y):return x+y

Main ideas:

  • 4 spaces for indentation.
  • Max ~88 chars per line.
  • Clear names (total_price not tp).
  • Add spaces around operators (x = y + z).

πŸ“Œ PEP 20 – The Zen of Python

Python’s philosophy. See it by typing:

import this

Key rules:

  • Explicit is better than implicit β†’ Be clear.
  • Simple is better than complex β†’ Don’t overcomplicate.
  • Readability counts β†’ Code should be easy to read.

πŸ“Œ PEP 257 – Docstring Conventions

How to write docstrings (function/class comments).

βœ… Example:

def greet(name: str) -> str:
    """Return a greeting message for the given name."""
    return f"Hello {name}"

πŸ“Œ PEP 234 – Iterators

Introduced the iterator protocol β†’ made for loops powerful.

for letter in "hello":
    print(letter)

πŸ“Œ PEP 343 – The with Statement

Introduced context managers. Automatically handles closing files, connections, etc.

βœ… Example:

with open("file.txt") as f:
    data = f.read()

❌ Example:

f = open("file.txt")
data = f.read()
f.close()  # you must remember this

πŸ“Œ PEP 484 – Type Hints

Added type hints β†’ makes code easier to read and check.

def add(x: int, y: int) -> int:
    return x + y

πŸ“Œ PEP 526 – Variable Annotations

Lets you add type hints to variables.

count: int = 0

πŸ“Œ PEP 572 – Assignment Expressions (:=)

Introduced the walrus operator. Assign a value inside an expression.

βœ… Example:

while (line := input("Type: ")) != "quit":
    print(line)

πŸ“Œ PEP 585 – Built-in Generics

Use built-in types directly for typing.

βœ… Example:

def get_numbers() -> list[int]:
    return [1, 2, 3]

❌ Old way:

from typing import List
def get_numbers() -> List[int]:
    return [1, 2, 3]

πŸ“Œ PEP 604 – Union Types

Simpler syntax for multiple possible types.

βœ… Example:

def square(x: int | float) -> float:
    return x * x

❌ Old way:

from typing import Union
def square(x: Union[int, float]) -> float:
    return x * x

πŸ“Œ PEP 563 & PEP 649 – Type Annotations Future

  • PEP 563 (postponed evaluation) β†’ annotations were stored as strings.
  • PEP 649 β†’ newer solution, keeps them efficient without breaking tools.

Result: type hints are fast and memory-friendly in new Python versions.


πŸ“Œ PEP 572 – Walrus Operator

Lets you assign inside conditions.

if (n := len([1, 2, 3])) > 2:
    print(f"List has {n} items")

πŸ“Œ PEP 618 – Extended zip()

Adds strict=True option. Raises error if zipped lists aren’t same length.

zip([1, 2], [3], strict=True)  # ❌ Error

πŸ“Œ PEP 622 – Pattern Matching (Structural)

Introduced match / case (Python 3.10). Like switch in other languages, but more powerful.

βœ… Example:

def handle(value):
    match value:
        case 0:
            return "zero"
        case [x, y]:
            return f"pair: {x}, {y}"
        case _:
            return "something else"

πŸ“Œ PEP 654 – Exception Groups

Handle multiple errors together.

try:
    ...
except* ValueError as e:
    print("value error")

πŸ“Œ PEP 701 – f-strings Everywhere

You can now use f-strings inside more places, like docstrings.


πŸ“Œ Packaging PEPs

These affect how Python projects are shared and installed:

  • PEP 427 – Wheels β†’ .whl files = faster installs.
  • PEP 440 – Versioning β†’ standard rules for versions (1.0.0, 2.1.3b1).
  • PEP 518 – pyproject.toml β†’ modern project config.
  • PEP 621 – Metadata in TOML β†’ standard way to write project info.

Example pyproject.toml:

[project]
name = "myapp"
version = "1.0.0"
dependencies = ["requests"]

πŸ“Œ Rare But Important PEPs

  • PEP 572 – Walrus Operator (again, because it’s easy to misuse).

  • PEP 622 – Pattern Matching can be tricky:

    • Order matters (like if/elif).
    • _ means β€œanything”.

βœ… Summary Table

PEP What it does Why it matters
8 Style guide Code looks clean & consistent
20 Zen of Python Philosophy: keep it simple, readable
257 Docstrings Standard way to explain code
234 Iterators Makes for loops powerful
343 with Auto-close files/resources
484 Type hints Easier to read/check functions
526 Variable annotations Type hints for variables
572 Walrus operator Assign inside expressions
585 Built-in generics Use list[int] instead of List[int]
604 Union types Use `int strinstead ofUnion`
622 Match/case Pattern matching (Python 3.10)
654 Exception groups Handle multiple errors
427 Wheel format Faster package installs
518 pyproject.toml Standard project config
621 Metadata in TOML Project info in one place

πŸš€ Final Thoughts

  • PEP 8 + PEP 20 = how to write and think in Python.
  • Type hints (PEP 484, 585, 604) = modern standard (2025).
  • Packaging PEPs (518, 621) = all new projects should use pyproject.toml.
  • Pattern matching (PEP 622) = powerful but use carefully.
  • Linters + formatters (black, ruff, mypy) β†’ enforce these rules automatically.

Python keeps evolving, but these PEPs are the ones you’ll use every day.