""" Python Unpacking Practice =========================== Concepts covered: 1. *args — collecting positional arguments into a tuple 2. **kwargs — collecting keyword arguments into a dict 3. * unpacking — spreading lists/tuples into function calls 4. ** unpacking — spreading dicts into keyword arguments 5. Merging lists with [*a, *b] and dicts with {**a, **b} 6. Tuple unpacking — first, *middle, last = sequence 7. @classmethod — alternative constructors using unpacking """ # ============================================================================= # 1. CONFIG CLASS # Demonstrates: **kwargs, ** unpacking, dict merging, @classmethod # ============================================================================= class Config: """Configuration manager using **kwargs for flexible settings.""" def __init__(self, name: str, **kwargs): self.name = name self.settings = kwargs def merge(self, other): """Merge two configs — other's settings win on conflicts.""" merged = {**self.settings, **other.settings} return Config(f"{self.name}+{other.name}", **merged) def display(self): """Display all settings using dict unpacking.""" print(f"[{self.name}]") for key, value in self.settings.items(): print(f" {key}: {value}") @classmethod def from_dict(cls, name: str, data: dict): """Alternative constructor — create Config from a dictionary.""" return cls(name, **data) def __repr__(self): return f"Config('{self.name}', {self.settings})" # ============================================================================= # 2. UNPACKING EXAMPLES — Reference snippets # ============================================================================= def unpacking_examples(): """Quick reference for all unpacking patterns.""" # --- *args: collect positional arguments --- def add(*args): return sum(args) print("=== *args ===") print(f" add(1, 2, 3) = {add(1, 2, 3)}") print(f" add(10, 20) = {add(10, 20)}") # --- **kwargs: collect keyword arguments --- def profile(**kwargs): return kwargs print("\n=== **kwargs ===") print(f" profile(name='Alice', age=25) = {profile(name='Alice', age=25)}") # --- * unpacking into function calls --- nums = [10, 20, 30] print(f"\n=== * unpack into call ===") print(f" add(*[10, 20, 30]) = {add(*nums)}") # --- Tuple unpacking --- numbers = [1, 2, 3, 4, 5] first, *middle, last = numbers print(f"\n=== Tuple unpacking ===") print(f" first={first}, middle={middle}, last={last}") a, b, *rest = numbers print(f" a={a}, b={b}, rest={rest}") # --- Merging lists --- list1 = [1, 2, 3] list2 = [4, 5, 6] combined = [*list1, *list2] print(f"\n=== Merge lists ===") print(f" [*{list1}, *{list2}] = {combined}") # --- Merging dicts --- defaults = {"color": "blue", "size": "medium"} custom = {"size": "large", "weight": "heavy"} merged = {**defaults, **custom} print(f"\n=== Merge dicts ===") print(f" defaults: {defaults}") print(f" custom: {custom}") print(f" merged: {merged}") # --- Swap variables --- a, b = 1, 2 a, b = b, a print(f"\n=== Swap ===") print(f" a={a}, b={b}") # --- Nested unpacking --- data = ("Alice", (90, 85, 92)) name, (t1, t2, t3) = data print(f"\n=== Nested unpacking ===") print(f" name={name}, scores={t1}, {t2}, {t3}") # ============================================================================= # 3. TESTS # ============================================================================= if __name__ == "__main__": # --- Unpacking reference examples --- unpacking_examples() # --- Config class --- print("\n=== Config: Basic Usage ===") c1 = Config("defaults", color="blue", size="medium", font="Arial") c1.display() print("\n=== Config: Merge ===") c2 = Config("custom", size="large", weight="bold") c3 = c1.merge(c2) c3.display() print("\n=== Config: From Dict ===") data = {"theme": "dark", "lang": "en"} c4 = Config.from_dict("prefs", data) c4.display() print("\n=== Config: Repr ===") print(f" {repr(c1)}") print(f" {repr(c3)}") print(f" {repr(c4)}")