Exceptions, Typing and Performance Tips

Harry · 14 Sep 2026 · 2 views
Advertisement
Advertisement

Handling Errors

try:
    result = 10 / int(input("Number: "))
except ValueError:
    print("That was not a number!")
except ZeroDivisionError:
    print("Cannot divide by zero!")
else:
    print(f"Result: {result}")
finally:
    print("Done")

Raising Your Own Exceptions

def withdraw(balance, amount):
    if amount > balance:
        raise ValueError("Insufficient funds")
    return balance - amount

Type Hints

Type hints document intent and let tools (mypy, IDEs) catch mistakes early.

from typing import List, Optional

def total(prices: List[float], discount: Optional[float] = None) -> float:
    t = sum(prices)
    return t * (1 - discount) if discount else t

Performance Tips

  • Prefer comprehensions and built-ins (sum, max, any) over manual loops.
  • Use in on sets/dicts for O(1) membership checks instead of lists.
  • Profile with cProfile before optimising; measure, don't guess.
  • Mind the GIL: use multiprocessing for CPU-bound work, threads for I/O.
  • Avoid big string concatenation; use str.join().

Key Points

  • try/except/else/finally makes handling errors explicit.
  • Type hints + typing improve clarity and tool support.
  • Profile first; the standard library is already well optimised.
Share this post:

Comments (0)

Please login or register to comment.