Part 14 / Stage 3
Python internals
Goal: Understand what Python does underneath (objects, dunder methods, attribute lookup, memory and bytecode) and use that knowledge to measure and speed up real programs. Time: ~1 hour
What you will learn
- Everything is an object: identity, type, value, names vs objects, reference counts
- The data model: the dunder methods behind
len(),[],in,for,bool(),()andhash() - Attribute access:
__dict__,getattr/setattr/hasattr,__getattr__ - Descriptors:
__get__,__set__,__set_name__, and how@propertyworks __slots__: smaller objects, and the trade-offs- How classes are made:
type(), class decorators,__init_subclass__, metaclasses - Memory management: reference counting, the garbage collector,
weakref,tracemalloc - Bytecode:
compile, code objects,dis, the interpreter loop - Measuring speed:
timeit,time.perf_counter,cProfile+pstats - Common speed-ups, and the golden rule: measure, don't guess
About "CPython 3.13": CPython is the standard Python you download from python.org. Some details here (reference counts, byte sizes, bytecode names) belong to CPython, not to the Python language. They were checked on CPython 3.13 and can differ in other versions. They are marked "CPython 3.13".
Topics in this part
Practice
Python workbench โ write and run code here
Press Run and Python 3.14 loads right in your browser (a one-time download of about 15 MB; after that it works offline). Your code never leaves this page. input() opens a small prompt window.
Write each answer in its own file with a main() function and the if __name__ == "__main__": guard. Reference counts and memory sizes are CPython details: the sample outputs were made on CPython 3.14. Where timing or memory is involved, the exercise prints a True/False check so your output can match exactly.
Exercise 1: Names, identity and reference counts
Scenario: A canteen app shares one menu list between screens, and you want to see exactly what = and .copy() do.
What to do: Inside main():
- Make
menu = ["idli", "dosa"], thenalias = menuandcopy = menu.copy(). - Print the type names of
menu, oftype(menu)and ofmain(usetype(...).__name__). - Print
menu == copy,menu is copy,menu is alias, and whetherid(menu) == id(alias). - Append
"vada"throughalias, then printmenuandcopy. - Save
start = sys.getrefcount(menu)and print it. Then print the change fromstartafter: puttingmenuin a dicttoday = {"breakfast": menu};del alias;today.clear().
Sample output:
type(menu): list
type(type(menu)): type
type(main): function
menu == copy: True
menu is copy: False
menu is alias: True
same id as alias: True
menu: ['idli', 'dosa', 'vada']
copy: ['idli', 'dosa']
getrefcount at start: 2
change after dict: 1
change after del alias: 0
change after clear: -1
๐ก Hint: The start is 2: menu and alias each hold one reference to the same list. On CPython 3.14 the interpreter can pass a local variable into a call as a borrowed reference, so getrefcount(menu) no longer adds its own temporary +1 the way it did on older versions. del alias and the dict going away each still take one reference off, so the last two changes are 1 - 1 = 0 and then -1.
Show the solution to Exercise 1
"""Exercise 1: Names, identity and reference counts.
Shows: id/type/value, `is` vs ==, aliases, and sys.getrefcount changes
(counts are a CPython detail; checked on CPython 3.14).
Run: python ex01.py (macOS/Linux: python3 ex01.py)
"""
import sys
def main() -> None:
menu = ["idli", "dosa"]
alias = menu
copy = menu.copy()
print("type(menu):", type(menu).__name__)
print("type(type(menu)):", type(type(menu)).__name__)
print("type(main):", type(main).__name__)
print("menu == copy:", menu == copy)
print("menu is copy:", menu is copy)
print("menu is alias:", menu is alias)
print("same id as alias:", id(menu) == id(alias))
alias.append("vada")
print("menu:", menu)
print("copy:", copy)
start = sys.getrefcount(menu)
print("getrefcount at start:", start)
today = {"breakfast": menu}
print("change after dict:", sys.getrefcount(menu) - start)
del alias
print("change after del alias:", sys.getrefcount(menu) - start)
today.clear()
print("change after clear:", sys.getrefcount(menu) - start)
if __name__ == "__main__":
main()
Exercise 2: A warehouse stock class that works with built-ins
Scenario: A warehouse tool wants len(), [], in, for and if to "just work" on its stock object.
What to do: Write a class Stock(items) that copies the dict of sku -> quantity and has:
__len__: number of SKUs.__getitem__(sku): the quantity (an unknown SKU raisesKeyError, like a dict).__contains__(sku):Trueonly if the SKU exists and its quantity is above 0.__iter__: loops over the SKUs in sorted order.__bool__:Trueif any SKU has quantity above 0.__call__(sku, qty): addsqtyto that SKU and returns the new quantity.
Then print the lines below. For the unknown SKU, catch KeyError and print Unknown SKU: with the error. Finally make empty = Stock({"SKU-7": 0}), print bool(empty), and print Reorder needed! using if not empty:.
Starting data:
STOCK = {"SKU-3": 0, "SKU-1": 40, "SKU-2": 12}
Sample output:
Items: 3
SKU-1 qty: 40
SKU-1 in stock: True
SKU-3 in stock: False
All SKUs: ['SKU-1', 'SKU-2', 'SKU-3']
Unknown SKU: 'SKU-9'
Restock SKU-3 by 5 -> 5
SKU-3 in stock: True
Empty warehouse has stock: False
Reorder needed!
๐ก Hint: list(stock) uses __iter__. __iter__ can simply return iter(sorted(self._items)).
Show the solution to Exercise 2
"""Exercise 2: A warehouse stock class that works with built-ins.
Shows: __len__, __getitem__, __contains__, __iter__, __bool__ and __call__.
Run: python ex02.py (macOS/Linux: python3 ex02.py)
"""
STOCK = {"SKU-3": 0, "SKU-1": 40, "SKU-2": 12}
class Stock:
def __init__(self, items: dict[str, int]) -> None:
self._items = dict(items)
def __len__(self) -> int:
return len(self._items)
def __getitem__(self, sku: str) -> int:
return self._items[sku]
def __contains__(self, sku: str) -> bool:
return self._items.get(sku, 0) > 0
def __iter__(self):
return iter(sorted(self._items))
def __bool__(self) -> bool:
return any(qty > 0 for qty in self._items.values())
def __call__(self, sku: str, qty: int) -> int:
self._items[sku] = self._items.get(sku, 0) + qty
return self._items[sku]
def main() -> None:
stock = Stock(STOCK)
print("Items:", len(stock))
print("SKU-1 qty:", stock["SKU-1"])
print("SKU-1 in stock:", "SKU-1" in stock)
print("SKU-3 in stock:", "SKU-3" in stock)
print("All SKUs:", list(stock))
try:
stock["SKU-9"]
except KeyError as error:
print("Unknown SKU:", error)
print("Restock SKU-3 by 5 ->", stock("SKU-3", 5))
print("SKU-3 in stock:", "SKU-3" in stock)
empty = Stock({"SKU-7": 0})
print("Empty warehouse has stock:", bool(empty))
if not empty:
print("Reorder needed!")
if __name__ == "__main__":
main()
Exercise 3: Coupon codes as dict keys and set members
Scenario: Users type coupon codes in any case, sometimes with spaces. "diwali50 " must count as the same coupon as "DIWALI50".
What to do:
- Write
Coupon(code)that storescode.strip().upper(), with__repr__returningCoupon('DIWALI50')style,__eq__comparing codes (returnNotImplementedfor non-coupons) and__hash__hashing the code. - Make a list of coupons from
CODES. Print whether the first two are equal and have the same hash. - Put them in a set and print it sorted by code.
- Make
discounts = {Coupon("DIWALI50"): 50, Coupon("HOLI20"): 20}and print the discount forCoupon(" holi20"). - Write
BrokenCouponwith__eq__only. PrintBrokenCoupon.__hash__, then try to put one in a set and print theTypeError.
Starting data:
CODES = ["DIWALI50", "diwali50", "Holi20", "HOLI20 ", "NEWUSER"]
Sample output:
Equal: True
Same hash: True
Unique: [Coupon('DIWALI50'), Coupon('HOLI20'), Coupon('NEWUSER')]
Discount for ' holi20': 20
BrokenCoupon.__hash__: None
Error: cannot use 'BrokenCoupon' as a set element (unhashable type: 'BrokenCoupon')
๐ก Hint: sorted(unique, key=lambda c: c.code). Hash exactly the field that __eq__ compares.
Show the solution to Exercise 3
"""Exercise 3: Coupon codes as dict keys and set members.
Shows: the __eq__ / __hash__ rules, and what happens without __hash__.
Run: python ex03.py (macOS/Linux: python3 ex03.py)
"""
CODES = ["DIWALI50", "diwali50", "Holi20", "HOLI20 ", "NEWUSER"]
class Coupon:
"""Coupons compare case-insensitively and ignore spaces."""
def __init__(self, code: str) -> None:
self.code = code.strip().upper()
def __repr__(self) -> str:
return f"Coupon({self.code!r})"
def __eq__(self, other: object) -> bool:
if not isinstance(other, Coupon):
return NotImplemented
return self.code == other.code
def __hash__(self) -> int:
return hash(self.code) # the same field __eq__ uses
class BrokenCoupon:
"""Defines __eq__ only, so Python sets __hash__ to None."""
def __init__(self, code: str) -> None:
self.code = code.strip().upper()
def __eq__(self, other: object) -> bool:
return isinstance(other, BrokenCoupon) and self.code == other.code
def main() -> None:
coupons = [Coupon(code) for code in CODES]
print("Equal:", coupons[0] == coupons[1])
print("Same hash:", hash(coupons[0]) == hash(coupons[1]))
unique = set(coupons)
print("Unique:", sorted(unique, key=lambda c: c.code))
discounts = {Coupon("DIWALI50"): 50, Coupon("HOLI20"): 20}
print("Discount for ' holi20':", discounts[Coupon(" holi20")])
print("BrokenCoupon.__hash__:", BrokenCoupon.__hash__)
try:
{BrokenCoupon("DIWALI50")}
except TypeError as error:
print("Error:", error)
if __name__ == "__main__":
main()
Exercise 4: A reusable BoundedNumber descriptor
Scenario: A school's report card has marks and attendance that must always stay between 0 and 100. What to do:
- Write a descriptor
BoundedNumber(low, high)with__set_name__(storenameandprivate_name = "_" + name),__get__(return the descriptor itself whenobj is None) and__set__, which raises:TypeError("<name> must be a number, got <value!r>")if the value is not anintorfloat;ValueError("<name> must be between <low> and <high>, got <value>")if it is out of range.
- Write
ReportCard(student, maths, science, attendance)with the three numbers asBoundedNumber(0, 100)fields, and a methodaverage()of maths and science. - Print the card, the average,
card.__dict__, and thenamestored onReportCard.mathsandReportCard.attendance. - Try
maths=105,science=-3,attendance="full"withsetattr, printing<ErrorType>: <message>. Then set maths to 95 and print the new average.
Sample output:
Asha: maths 91, science 84, attendance 96%
Average: 87.5
Stored as: {'student': 'Asha', '_maths': 91, '_science': 84, '_attendance': 96}
Field names: maths attendance
ValueError: maths must be between 0 and 100, got 105
ValueError: science must be between 0 and 100, got -3
TypeError: attendance must be a number, got 'full'
Updated average: 89.5
๐ก Hint: ReportCard.maths reads the descriptor on the class, so obj is None and __get__ returns the descriptor; then .name works. Use except (ValueError, TypeError) as error: and type(error).__name__.
Show the solution to Exercise 4
"""Exercise 4: A reusable BoundedNumber descriptor for a report card.
Shows: __set_name__, __get__ and __set__; one field class used many times.
Run: python ex04.py (macOS/Linux: python3 ex04.py)
"""
class BoundedNumber:
"""A number that must stay between low and high (inclusive)."""
def __init__(self, low: float, high: float) -> None:
self.low = low
self.high = high
def __set_name__(self, owner, name: str) -> None:
self.name = name
self.private_name = "_" + name
def __get__(self, obj, objtype=None):
if obj is None:
return self
return getattr(obj, self.private_name)
def __set__(self, obj, value) -> None:
if not isinstance(value, (int, float)):
raise TypeError(f"{self.name} must be a number, got {value!r}")
if not self.low <= value <= self.high:
raise ValueError(
f"{self.name} must be between {self.low} and {self.high}, got {value}"
)
setattr(obj, self.private_name, value)
class ReportCard:
maths = BoundedNumber(0, 100)
science = BoundedNumber(0, 100)
attendance = BoundedNumber(0, 100)
def __init__(self, student: str, maths: int, science: int, attendance: int):
self.student = student
self.maths = maths
self.science = science
self.attendance = attendance
def average(self) -> float:
return (self.maths + self.science) / 2
def main() -> None:
card = ReportCard("Asha", 91, 84, 96)
print(f"{card.student}: maths {card.maths}, science {card.science}, "
f"attendance {card.attendance}%")
print("Average:", card.average())
print("Stored as:", card.__dict__)
print("Field names:", ReportCard.maths.name, ReportCard.attendance.name)
for field, bad in [("maths", 105), ("science", -3), ("attendance", "full")]:
try:
setattr(card, field, bad)
except (ValueError, TypeError) as error:
print(f"{type(error).__name__}: {error}")
card.maths = 95
print("Updated average:", card.average())
if __name__ == "__main__":
main()
Exercise 5: Slotted GPS points for a delivery fleet
Scenario: A delivery app stores millions of GPS points, so each point must be small, and unknown fields must be rejected. What to do:
- Write
GpsPointwith__slots__ = ("bike", "lat", "lon")and an__init__(self, **fields)that sets each field withsetattr. - Write
PlainGpsPoint, the same class without__slots__. - Loop over
ROWS: build aGpsPoint(**row), print<bike> at (<lat>, <lon>)(readbikewithgetattr). If anAttributeErrorhappens, printRejected <bike>: <error>. - For a point from the first row, print
hasattr(point, "__dict__"),hasattr(point, "speed")andgetattr(point, "speed", 0). - Write
memory_for(cls)that usestracemallocto measure the bytes used while 50,000 objects ofclsare alive. Print whether slots use less memory, and whether the saving is at least 25%.
Starting data:
ROWS = [
{"bike": "MH12-4821", "lat": 18.5204, "lon": 73.8567},
{"bike": "DL3C-0917", "lat": 28.6139, "lon": 77.2090},
{"bike": "KA01-5530", "lat": 12.9716, "lon": 77.5946, "speed": 32},
]
COUNT = 50_000
Sample output:
MH12-4821 at (18.5204, 73.8567)
DL3C-0917 at (28.6139, 77.209)
Rejected KA01-5530: 'GpsPoint' object has no attribute 'speed' and no __dict__ for setting new attributes
Has __dict__: False
Has speed: False
Speed or default: 0
Slots use less memory: True
Saving is at least 25%: True
๐ก Hint: Inside memory_for: tracemalloc.start(), build the list, used = tracemalloc.get_traced_memory()[0], then tracemalloc.stop(). The saving check is slim <= plain * 0.75.
Show the solution to Exercise 5
"""Exercise 5: Slotted GPS points for a delivery fleet.
Shows: __slots__, setattr/getattr/hasattr, and measuring memory with tracemalloc.
Run: python ex05.py (macOS/Linux: python3 ex05.py)
"""
import tracemalloc
ROWS = [
{"bike": "MH12-4821", "lat": 18.5204, "lon": 73.8567},
{"bike": "DL3C-0917", "lat": 28.6139, "lon": 77.2090},
{"bike": "KA01-5530", "lat": 12.9716, "lon": 77.5946, "speed": 32},
]
COUNT = 50_000
class GpsPoint:
__slots__ = ("bike", "lat", "lon")
def __init__(self, **fields) -> None:
for name, value in fields.items():
setattr(self, name, value)
class PlainGpsPoint:
def __init__(self, **fields) -> None:
for name, value in fields.items():
setattr(self, name, value)
def memory_for(cls) -> int:
"""Bytes used while COUNT objects of cls are alive."""
tracemalloc.start()
points = [cls(bike="MH12-4821", lat=18.52, lon=73.85) for _ in range(COUNT)]
used = tracemalloc.get_traced_memory()[0]
tracemalloc.stop()
del points
return used
def main() -> None:
for row in ROWS:
try:
point = GpsPoint(**row)
except AttributeError as error:
print(f"Rejected {row['bike']}: {error}")
continue
print(f"{getattr(point, 'bike')} at ({point.lat}, {point.lon})")
point = GpsPoint(**ROWS[0])
print("Has __dict__:", hasattr(point, "__dict__"))
print("Has speed:", hasattr(point, "speed"))
print("Speed or default:", getattr(point, "speed", 0))
plain = memory_for(PlainGpsPoint)
slim = memory_for(GpsPoint)
print("Slots use less memory:", slim < plain)
print("Saving is at least 25%:", slim <= plain * 0.75)
if __name__ == "__main__":
main()
Exercise 6: Report exporters as plugins
Scenario: A billing app exports reports in several formats, and new formats must plug in without editing the old code. What to do:
- Write a base class
Exporterwith a class dictformatsand an__init_subclass__(cls, fmt, **kwargs)that registers each subclass underfmt. - Write
CsvExporter(Exporter, fmt="csv")(headername,amount, thenname,amountlines) andTextExporter(Exporter, fmt="text")(lines likef"{name:<6} โน{amount:,}"). - Write a class decorator
with_footerthat wraps the class'sexportso the output ends with a new line(<n> rows). Use it onCsvExporteronly. - Write
export(fmt, rows)that looks up the class, creates it and callsexport(rows). For an unknown format returnUnknown format '<fmt>'. Available: <sorted names>. - Print the formats, the csv and text exports, then create a
TsvExporterwithtype()(noclassstatement) and export the first row with tabs shown as<TAB>. Finally try"pdf".
Starting data:
ROWS = [("Asha", 1760), ("Ravi", 540), ("Meera", 2999)]
Sample output:
Formats: ['csv', 'text']
--- csv ---
name,amount
Asha,1760
Ravi,540
Meera,2999
(3 rows)
--- text ---
Asha โน1,760
Ravi โน540
Meera โน2,999
--- tsv ---
Asha <TAB> 1760
--- pdf ---
Unknown format 'pdf'. Available: csv, text, tsv
๐ก Hint: In the decorator, save original = cls.export and set cls.export to a new function that calls original(self, rows). Extra keyword arguments to type() are passed on to __init_subclass__, just like in a class line: type("TsvExporter", (Exporter,), {"export": tsv_export}, fmt="tsv").
Show the solution to Exercise 6
"""Exercise 6: Report exporters as plugins.
Shows: a plugin registry with __init_subclass__, a class decorator,
and type() creating a class at run time.
Run: python ex06.py (macOS/Linux: python3 ex06.py)
"""
ROWS = [("Asha", 1760), ("Ravi", 540), ("Meera", 2999)]
class Exporter:
formats: dict[str, type] = {}
def __init_subclass__(cls, fmt: str, **kwargs) -> None:
super().__init_subclass__(**kwargs)
Exporter.formats[fmt] = cls
def export(self, rows: list[tuple[str, int]]) -> str:
raise NotImplementedError
def with_footer(cls):
"""Class decorator: wrap export() so the output ends with a row count."""
original = cls.export
def export(self, rows):
return original(self, rows) + f"\n({len(rows)} rows)"
cls.export = export
return cls
@with_footer
class CsvExporter(Exporter, fmt="csv"):
def export(self, rows):
return "name,amount\n" + "\n".join(f"{n},{a}" for n, a in rows)
class TextExporter(Exporter, fmt="text"):
def export(self, rows):
return "\n".join(f"{n:<6} โน{a:,}" for n, a in rows)
def tsv_export(self, rows):
return "\n".join(f"{n}\t{a}" for n, a in rows)
def export(fmt: str, rows: list[tuple[str, int]]) -> str:
if fmt not in Exporter.formats:
available = ", ".join(sorted(Exporter.formats))
return f"Unknown format {fmt!r}. Available: {available}"
return Exporter.formats[fmt]().export(rows)
def main() -> None:
print("Formats:", sorted(Exporter.formats))
print("--- csv ---")
print(export("csv", ROWS))
print("--- text ---")
print(export("text", ROWS))
# A class made with type() registers too: keyword arguments go to
# __init_subclass__.
type("TsvExporter", (Exporter,), {"export": tsv_export}, fmt="tsv")
print("--- tsv ---")
print(export("tsv", ROWS[:1]).replace("\t", " <TAB> "))
print("--- pdf ---")
print(export("pdf", ROWS))
if __name__ == "__main__":
main()
Exercise 7: Memory detective
Scenario: A web app's login sessions are not being freed, and a log loader uses too much memory. Investigate both.
What to do: Write a class Session(user) with attributes user and partner = None. In main(), print the numbered lines below:
- Make
asha, takeweakref.ref(asha),del asha, and print whether it is still alive. - Turn the GC off with
gc.disable(). Makeraviandmeera, link them to each other throughpartner(a cycle), take a weak reference toravi, and delete both names. Print whetherraviis alive, callgc.collect(), print again, thengc.enable(). - Put sessions
kiran(key"s1") andpriya(key"s2") in aweakref.WeakValueDictionarycalledactive. Print the sorted keys,del kiran, print them again, then print who"s2"belongs to and whether itis priya. - Write
load_all_logs()(returns[f"2026-03-01 request {n} " + "." * 100 for n in range(20_000)]) andload_log_summary()(returns{"requests": 20_000, "errors": 37}). Writebytes_used(func)withtracemalloc. Print the name of the bigger function, whether it uses over 1 MiB, and whether the summary uses under 1 KiB.
Sample output:
1. asha alive after del: False
2. ravi alive after del: True
2. ravi alive after gc.collect(): False
3. active sessions: ['s1', 's2']
3. after kiran logs out: ['s2']
3. s2 belongs to: priya | same object: True
4. memory hog: load_all_logs
4. uses over 1 MiB: True
4. summary under 1 KiB: True
๐ก Hint: "alive" is ref() is not None. For step 4, build a dict {func.__name__: bytes_used(func)} and use max(sizes, key=sizes.get).
Show the solution to Exercise 7
"""Exercise 7: Memory detective.
Shows: reference counting, a reference cycle cleaned by gc.collect(),
weakref.ref, WeakValueDictionary, and tracemalloc to compare two functions.
Run: python ex07.py (macOS/Linux: python3 ex07.py)
"""
import gc
import tracemalloc
import weakref
class Session:
def __init__(self, user: str) -> None:
self.user = user
self.partner = None
def load_all_logs() -> list[str]:
return [f"2026-03-01 request {n} " + "." * 100 for n in range(20_000)]
def load_log_summary() -> dict[str, int]:
return {"requests": 20_000, "errors": 37}
def bytes_used(func) -> int:
tracemalloc.start()
result = func()
used = tracemalloc.get_traced_memory()[0]
tracemalloc.stop()
del result
return used
def main() -> None:
# 1. Plain reference counting
asha = Session("asha")
asha_ref = weakref.ref(asha)
del asha
print("1. asha alive after del:", asha_ref() is not None)
# 2. A cycle survives del until the collector runs
gc.disable()
ravi, meera = Session("ravi"), Session("meera")
ravi.partner, meera.partner = meera, ravi
ravi_ref = weakref.ref(ravi)
del ravi, meera
print("2. ravi alive after del:", ravi_ref() is not None)
gc.collect()
print("2. ravi alive after gc.collect():", ravi_ref() is not None)
gc.enable()
# 3. A cache that does not keep sessions alive
active = weakref.WeakValueDictionary()
kiran, priya = Session("kiran"), Session("priya")
active["s1"], active["s2"] = kiran, priya
print("3. active sessions:", sorted(active))
del kiran
print("3. after kiran logs out:", sorted(active))
print("3. s2 belongs to:", active["s2"].user, "| same object:",
active["s2"] is priya)
# 4. Which loader is the memory hog?
sizes = {}
for func in (load_all_logs, load_log_summary):
sizes[func.__name__] = bytes_used(func)
hog = max(sizes, key=sizes.get)
print("4. memory hog:", hog)
print("4. uses over 1 MiB:", sizes[hog] > 1024 * 1024)
print("4. summary under 1 KiB:", sizes["load_log_summary"] < 1024)
if __name__ == "__main__":
main()
Exercise 8: Find and fix the slow function
Scenario: A newsletter job cleans 4,000 sign-up emails, finds duplicates and counts domains. It is slow. Measure, don't guess. What to do:
- Write
clean_emails(raw)(strip and lower-case each email),find_duplicates(emails)(the slow version:sorted({e for e in emails if emails.count(e) > 1})) andcount_domains(emails)(a dict fromCounterof the part after@). - Write
run_job(raw, find=find_duplicates)that cleans the emails and returns(find(emails), count_domains(emails)). - Print the number of sign-ups, the number of duplicates, the first three, and the domain counts sorted by name.
- Write
slowest_function(raw): profilerun_job(raw)withcProfile, then usepstats.Stats(profiler).get_stats_profile().func_profiles(a dict of function name โ profile info) to return the one of your three functions with the biggestcumtime. Print it. - Write
find_duplicates_fastwithCounter. Print whetherrun_jobgives the same result with it, and whether it is at least 10 times faster, usingtimeit.timeit(lambda: ..., number=3)for both.
Starting data:
import random
DOMAINS = ["mail.example.com", "post.example.in", "inbox.example.org"]
def make_signups(count: int) -> list[str]:
rng = random.Random(8) # fixed seed: same data every run
return [
f" User{rng.randint(1, count)}@{rng.choice(DOMAINS)} "
for _ in range(count)
]
# raw = make_signups(4_000)
Sample output:
Sign-ups: 4000
Duplicate emails: 543
First three: ['[email protected]', '[email protected]', '[email protected]']
Domains: {'inbox.example.org': 1331, 'mail.example.com': 1350, 'post.example.in': 1319}
Slowest function: find_duplicates
Same result after fix: True
At least 10x faster: True
๐ก Hint: Compare tottime and cumtime for find_duplicates: its own tottime is small, because the time is spent inside the built-in list.count it calls. That is why you pick by cumtime. Each item in func_profiles has .cumtime and .tottime.
Show the solution to Exercise 8
"""Exercise 8: Find and fix the slow function in a newsletter job.
Shows: cProfile + pstats (get_stats_profile) to find the slowest function,
a fix with collections.Counter, and timeit to compare before and after.
Run: python ex08.py (macOS/Linux: python3 ex08.py)
"""
import cProfile
import pstats
import random
import timeit
from collections import Counter
DOMAINS = ["mail.example.com", "post.example.in", "inbox.example.org"]
def make_signups(count: int) -> list[str]:
rng = random.Random(8) # fixed seed: same data every run
return [
f" User{rng.randint(1, count)}@{rng.choice(DOMAINS)} "
for _ in range(count)
]
def clean_emails(raw: list[str]) -> list[str]:
return [email.strip().lower() for email in raw]
def find_duplicates(emails: list[str]) -> list[str]:
"""Emails that signed up more than once (slow version)."""
return sorted({email for email in emails if emails.count(email) > 1})
def find_duplicates_fast(emails: list[str]) -> list[str]:
counts = Counter(emails)
return sorted(email for email, times in counts.items() if times > 1)
def count_domains(emails: list[str]) -> dict[str, int]:
return dict(Counter(email.split("@")[1] for email in emails))
def run_job(raw: list[str], find=find_duplicates) -> tuple[list[str], dict]:
emails = clean_emails(raw)
return find(emails), count_domains(emails)
def slowest_function(raw: list[str]) -> str:
"""Profile run_job and return the name of our function with the most cumtime."""
profiler = cProfile.Profile()
profiler.enable()
run_job(raw)
profiler.disable()
profile = pstats.Stats(profiler).get_stats_profile()
ours = {"clean_emails", "find_duplicates", "count_domains"}
timings = {
name: info.cumtime
for name, info in profile.func_profiles.items()
if name in ours
}
return max(timings, key=timings.get)
def main() -> None:
raw = make_signups(4_000)
duplicates, domains = run_job(raw)
print("Sign-ups:", len(raw))
print("Duplicate emails:", len(duplicates))
print("First three:", duplicates[:3])
print("Domains:", dict(sorted(domains.items())))
print("Slowest function:", slowest_function(raw))
fixed = run_job(raw, find=find_duplicates_fast)
print("Same result after fix:", fixed == (duplicates, domains))
before = timeit.timeit(lambda: run_job(raw), number=3)
after = timeit.timeit(lambda: run_job(raw, find=find_duplicates_fast), number=3)
print("At least 10x faster:", before / after >= 10)
if __name__ == "__main__":
main()
Common mistakes
| Mistake | Why it is wrong | Fix |
|---|---|---|
if price is 100: |
is checks identity, not value; may be True or False |
== for values; is only for None |
Reading sys.getrefcount as the exact number of names |
It adds 1 for its own argument; immortal objects show a huge number | Compare changes in the count |
__eq__ without __hash__ |
Objects become unhashable (no sets, no dict keys) | Add __hash__ using the same fields |
__getattr__ that returns None for unknown names |
Typos never fail; hasattr is always True |
Raise AttributeError |
Descriptor storing the value on self (the descriptor) |
All instances share one value | Store on obj, e.g. setattr(obj, self.private_name, value) |
__slots__ "for speed" on a few objects |
Little gain, and you lose flexibility | Use it only for many objects, after measuring |
| A metaclass for a simple registry | Hard to read; metaclass conflicts | __init_subclass__ or a class decorator |
Timing with time.time() and one run |
Low precision; one run is noisy | timeit or time.perf_counter, many runs |
| Optimising before profiling | You fix the wrong part | cProfile first, then fix the top function |
Quick recap
- Every value is an object with an identity, a type and a value; names are just labels;
delremoves a name. - CPython frees an object when its reference count hits 0; the
gcmodule cleans up reference cycles;weakrefpoints without keeping alive. - Built-ins call dunder methods:
lenโ__len__,inโ__contains__,forโ__iter__; equal objects need equal hashes. - Attributes live in
__dict__;getattr/setattr/hasattrwork with string names;__getattr__is only a fallback. - Descriptors (
__get__/__set__/__set_name__) are reusable attribute logic;@propertyis one. __slots__saves memory for many objects but blocks new attributes.typemakes classes; prefer class decorators and__init_subclass__over metaclasses.- Code is compiled to bytecode (
disshows it); measure withtimeit,perf_counter,cProfilebefore you change anything.
Checklist
- I can explain identity, type and value, and the
+1insys.getrefcount. - I can make a class work with
len,[],in,for,booland(), and follow the hash rules. - I can use
getattr/setattr/hasattrand write a__getattr__fallback. - I can write a validated descriptor field and explain how
@propertyworks. - I can measure the memory saved by
__slots__withtracemalloc. - I can build a plugin registry with
__init_subclass__. - I can show a reference cycle being collected by
gc.collect(). - I can profile a program with
cProfile, find the slow function, fix it and prove it is faster.