added unpacking basics
This commit is contained in:
1 parent
5bf57d9fe6
commit
e1830e0fb5
2 files changed
+187
No files matched your search
@@ -0,0 +1,48 @@
|
||||
# <!-- Create a Config class:
|
||||
|
||||
# __init__ takes name and any number of **settings
|
||||
# Store settings as a dict
|
||||
# Add a merge method that takes another Config and merges their settings (second one wins on conflicts)
|
||||
# Add a display method that unpacks and prints each setting
|
||||
# Add a class method from_dict that creates a Config from a dictionary using ** unpacking -->
|
||||
import itertools
|
||||
class Config:
|
||||
|
||||
def __init__(self, name, **kwargs):
|
||||
self.name = name
|
||||
self.settings = kwargs # is this the way to store the dict? what happens if there are multiple settings??
|
||||
|
||||
def merge(self, new_settings):
|
||||
merged = {**self.settings, **new_settings.settings}
|
||||
return Config("m", **merged) # note down my mistakes for revisiting later
|
||||
|
||||
def display(self):
|
||||
for i, j in self.settings.items():
|
||||
print(f"{i}: {j}")
|
||||
|
||||
@classmethod # did i learn classmethod? i woulld need a recap
|
||||
def from_dict(cls, name, dict: dict):
|
||||
return cls(name, **dict)
|
||||
|
||||
|
||||
c1 = Config("defaults", color="blue", size="medium", font="Arial")
|
||||
c2 = Config("custom", size="large", weight="bold")
|
||||
|
||||
c1.display()
|
||||
# color: blue
|
||||
# size: medium
|
||||
# font: Arial
|
||||
|
||||
c3 = c1.merge(c2)
|
||||
c3.display()
|
||||
# color: blue
|
||||
# size: large (overwritten by c2)
|
||||
# font: Arial
|
||||
# weight: bold (new from c2)
|
||||
|
||||
# From dict
|
||||
data = {"theme": "dark", "lang": "en"}
|
||||
c4 = Config.from_dict("prefs", data)
|
||||
c4.display()
|
||||
# theme: dark
|
||||
# lang: en
|
||||
@@ -0,0 +1,139 @@
|
||||
"""
|
||||
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)}")
|
||||
Reference in new issue
Block a user