Master modern Python: unit testing, data classes, and type hints for production-ready code.
Write clean, testable, and maintainable Python code like a professional.
unittest module to ensure your code works correctly.import unittest
class TestCalculator(unittest.TestCase):
def test_add(self):
self.assertEqual(add(2, 3), 5)
def test_subtract(self):
self.assertEqual(subtract(5, 3), 2)self.assertEqual(a, b) # a == b
self.assertNotEqual(a, b) # a != b
self.assertTrue(x) # x is True
self.assertFalse(x) # x is False
self.assertIsNone(x) # x is None
self.assertIn(a, b) # a in b
self.assertRaises(Error, func) # func raises Errorclass TestDatabase(unittest.TestCase):
def setUp(self):
# Runs before each test
self.db = Database()
def tearDown(self):
# Runs after each test
self.db.close()
def test_insert(self):
self.db.insert("data")
self.assertEqual(len(self.db), 1)# At the end of your file:
if __name__ == '__main__':
unittest.main()
# Or from command line:
# python -m unittest test_file.pytest_pytest for more features...
----------------------------------------------------------------------
Ran 3 tests in 0.001s
OK
import unittestclass TestX(unittest.TestCase):def test_something(self):self.assertEqual(actual, expected)if __name__ == '__main__': unittest.main()Review feedback below
@dataclass decorator for cleaner, more concise class definitions with automatic method generation.from dataclasses import dataclass
@dataclass
class Person:
name: str
age: int
email: str = "" # Default value
# Automatically gets __init__, __repr__, __eq__
p = Person("Alice", 30)
print(p) # Person(name='Alice', age=30, email='')@dataclass(order=True) # Enables <, >, <=, >=
class Product:
name: str
price: float
# For immutable (hashable) objects:
@dataclass(frozen=True)
class Point:
x: float
y: floatfrom dataclasses import dataclass, field
@dataclass
class ShoppingCart:
items: list = field(default_factory=list) # Mutable default
owner: str = "Guest"
def total(self):
return sum(item.price for item in self.items)@dataclass
class Rectangle:
width: float
height: float
area: float = field(init=False) # Not in __init__
def __post_init__(self):
self.area = self.width * self.heightfield(default_factory=list) for mutable defaultsfrozen=True makes instances immutable and hashable__post_init__ runs after generated __init__Person(name='Alice', age=30, email='alice@email.com')
Rectangle(width=5, height=3, area=15)
from dataclasses import dataclass, field@dataclass above classname: str, age: intemail: str = ""items: list = field(default_factory=list)Review feedback below
def greet(name: str) -> str:
return f"Hello, {name}!"
def add(a: int, b: int) -> int:
return a + b
age: int = 25
name: str = "Alice"
is_active: bool = Truefrom typing import List, Dict, Tuple, Set, Optional
def process_names(names: List[str]) -> List[str]:
return [name.upper() for name in names]
def get_user(id: int) -> Dict[str, any]:
return {"id": id, "name": "Alice"}
coordinates: Tuple[float, float] = (3.5, 4.2)
unique_ids: Set[int] = {1, 2, 3}from typing import Optional, Union
def find_user(id: int) -> Optional[str]:
# Returns str or None
return "Alice" if id == 1 else None
def process(value: Union[int, str]) -> str:
# Accepts int or str
return str(value)from typing import Callable, TypeAlias
# Type alias
UserId: TypeAlias = int
UserDict: TypeAlias = Dict[str, any]
# Function type
def apply(func: Callable[[int], int], value: int) -> int:
return func(value)mypy for static type checkingint | str instead of Union[int, str]Hello, Alice!
Sum: 15
Names: ['ALICE', 'BOB']
User: Alice (or None)
from typing import List, Dict, Optionaldef func(name: str):def func() -> int:List[str] Dict: Dict[str, int]Optional[str] = str | NoneReview feedback below