← Interview prep

Python interview questions

Python language, data structures, and common interview traps.

100 questions · Page 3 of 5

Want the full pack? Interview packs · Mock interview · Mentora

Page 3 of 5

Questions 41–60 of 100 · 0 of 20 on this page marked learned

41.python-0041Mediummid

Implement the iterator protocol for a class, and explain iterables versus iterators.

An iterable has __iter__ returning an iterator; an iterator has __next__, which returns the next value or raises StopIteration, and its own __iter__ returning itself. Containers should be iterables that return a fresh iterator each time, so they can be looped over repeatedly.

Full answer
python
class Countdown:
    def __init__(self, start): self.start = start
    def __iter__(self): return CountdownIterator(self.start)

class CountdownIterator:
    def __init__(self, n): self.n = n
    def __iter__(self): return self
    def __next__(self):
        if self.n <= 0:
            raise StopIteration
        self.n -= 1
        return self.n + 1

c = Countdown(3)
print(list(c), list(c))
it = iter(c)
print(next(it), next(it), next(it), next(it, "done"))
it2 = iter(c)
print(list(it2), list(it2))

Output:

text
[3, 2, 1] [3, 2, 1]
3 2 1 done
[3, 2, 1] []

Looping over Countdown twice works because each iter() call creates a new iterator. The iterator itself is single use: after it is exhausted, a second list() returns an empty list. next(it, default) returns the default instead of raising StopIteration. In practice, writing __iter__ as a generator function (def __iter__(self): yield from range(self.start, 0, -1)) gives the same behaviour with less code. for loops, list(), sum() and unpacking all use this protocol.

python
class Countdown:
    def __init__(self, start): self.start = start
    def __iter__(self): return CountdownIterator(self.start)

class CountdownIterator:
    def __init__(self, n): self.n = n
    def __iter__(self): return self
    def __next__(self):
        if self.n <= 0:
            raise StopIteration
        self.n -= 1
        return self.n + 1

c = Countdown(3)
print(list(c), list(c))
it = iter(c)
print(next(it), next(it), next(it), next(it, "done"))
it2 = iter(c)
print(list(it2), list(it2))

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Iterables return iterators from __iter__
  • Iterators implement __next__ and raise StopIteration
  • Containers should return fresh iterators
  • Iterators are single use
  • Generators simplify __iter__

Common mistakes

  • Returning self from a container's __iter__
  • Forgetting StopIteration

Follow-ups

  • How does a for loop use these methods?
  • What does iter(callable, sentinel) do?

Tips

  • Separate iterable from iterator
42.python-0042Mediummid

Which itertools functions come up most in interviews? Show groupby, chain, islice and combinations.

chain joins iterables, islice slices any iterator lazily, groupby groups consecutive items with the same key (so sort first), and combinations and permutations generate selections. accumulate gives running totals and pairwise gives neighbouring pairs. They are lazy and memory-efficient.

Full answer
python
from itertools import chain, islice, groupby, combinations, accumulate, pairwise, count
print(list(chain([1, 2], (3,), "ab")))
print(list(islice(count(10, 5), 4)))
sales = [("Pune", 3), ("Leeds", 5), ("Pune", 2)]
print([(city, sum(n for _, n in grp)) for city, grp in groupby(sales, key=lambda s: s[0])])
print([(city, sum(n for _, n in grp)) for city, grp in groupby(sorted(sales), key=lambda s: s[0])])
print(list(combinations("ABC", 2)))
print(list(accumulate([3, 1, 4])), list(pairwise([1, 3, 6])))

Output:

text
[1, 2, 3, 'a', 'b']
[10, 15, 20, 25]
[('Pune', 3), ('Leeds', 5), ('Pune', 2)]
[('Leeds', 5), ('Pune', 5)]
[('A', 'B'), ('A', 'C'), ('B', 'C')]
[3, 4, 8] [(1, 3), (3, 6)]

The first groupby shows the classic mistake: unsorted data produces two separate 'Pune' groups because only consecutive items are grouped. Sorting first gives one group per city. islice takes four values from the infinite count without building anything large. combinations('ABC', 2) yields the three unordered pairs. accumulate gives running totals and pairwise (Python 3.10+) yields neighbouring pairs, useful for differences between readings.

python
from itertools import chain, islice, groupby, combinations, accumulate, pairwise, count
print(list(chain([1, 2], (3,), "ab")))
print(list(islice(count(10, 5), 4)))
sales = [("Pune", 3), ("Leeds", 5), ("Pune", 2)]
print([(city, sum(n for _, n in grp)) for city, grp in groupby(sales, key=lambda s: s[0])])
print([(city, sum(n for _, n in grp)) for city, grp in groupby(sorted(sales), key=lambda s: s[0])])
print(list(combinations("ABC", 2)))
print(list(accumulate([3, 1, 4])), list(pairwise([1, 3, 6])))

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • chain concatenates iterables
  • islice slices lazily
  • groupby needs sorted input
  • combinations and permutations generate selections
  • accumulate and pairwise for running values

Common mistakes

  • Using groupby on unsorted data
  • Materialising infinite iterators

Follow-ups

  • How would you batch an iterator into chunks?
  • What does itertools.product do?

Tips

  • Sort before groupby
43.python-0043Mediummid

How do functools.lru_cache, cache and partial work?

lru_cache memoises a function's results keyed by its arguments, with an optional size limit, and functools.cache is the unbounded version. Arguments must be hashable. partial fixes some arguments of a function to create a simpler callable.

Full answer
python
from functools import lru_cache, partial
calls = 0

@lru_cache(maxsize=None)
def fib(n):
    global calls
    calls += 1
    return n if n < 2 else fib(n - 1) + fib(n - 2)

print(fib(80), calls, fib.cache_info())
try:
    lru_cache()(lambda xs: sum(xs))([1, 2])
except TypeError as e:
    print("TypeError:", e)

def price_with_tax(amount, rate):
    return round(amount * (1 + rate), 2)
gst18 = partial(price_with_tax, rate=0.18)
print(gst18(100), gst18.func.__name__, gst18.keywords)

Output:

text
23416728348467685 81 CacheInfo(hits=78, misses=81, maxsize=None, currsize=81)
TypeError: unhashable type: 'list'
118.0 price_with_tax {'rate': 0.18}

Without caching, fib(80) would make billions of calls; with it, each value from 0 to 80 is computed once, so calls is 81. cache_info() shows hits and misses. A list argument fails because cache keys must be hashable. Cached functions keep results alive for the life of the process, so bound the size for open-ended inputs and avoid caching methods on instances without care, since self becomes part of the key and keeps objects alive. partial builds a one-argument GST calculator from a general function.

python
from functools import lru_cache, partial
calls = 0

@lru_cache(maxsize=None)
def fib(n):
    global calls
    calls += 1
    return n if n < 2 else fib(n - 1) + fib(n - 2)

print(fib(80), calls, fib.cache_info())
try:
    lru_cache()(lambda xs: sum(xs))([1, 2])
except TypeError as e:
    print("TypeError:", e)

def price_with_tax(amount, rate):
    return round(amount * (1 + rate), 2)
gst18 = partial(price_with_tax, rate=0.18)
print(gst18(100), gst18.func.__name__, gst18.keywords)

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • lru_cache memoises by arguments
  • cache is unbounded
  • Arguments must be hashable
  • Cached values live for the process
  • partial fixes arguments

Common mistakes

  • Caching functions with side effects
  • Unbounded caches on unbounded inputs

Follow-ups

  • How would you cache with expiry?
  • Why can lru_cache on methods leak memory?

Tips

  • Show cache_info
44.python-0044Mediummid

What is the method resolution order, and how does super() behave with multiple inheritance?

The MRO is the order in which Python searches classes for an attribute, computed with C3 linearisation; it keeps subclasses before parents and preserves the order of bases. super() calls the next class in the MRO of the object's type, not simply the parent, which is what makes cooperative multiple inheritance work.

Full answer
python
class Base:
    def greet(self): return ["Base"]
class Left(Base):
    def greet(self): return ["Left"] + super().greet()
class Right(Base):
    def greet(self): return ["Right"] + super().greet()
class Child(Left, Right):
    def greet(self): return ["Child"] + super().greet()

print([c.__name__ for c in Child.__mro__])
print(Child().greet())
print(Left().greet())

Output:

text
['Child', 'Left', 'Right', 'Base', 'object']
['Child', 'Left', 'Right', 'Base']
['Left', 'Base']

For Child, the MRO is Child, Left, Right, Base, object. Inside Left.greet, super() therefore calls Right.greet, not Base.greet, even though Left's parent is Base. Each class appears once, so Base runs exactly once. For a plain Left instance, the MRO is Left, Base, object, and the same super() call reaches Base. Cooperative classes must all call super() and accept compatible arguments (often **kwargs) for this to work.

python
class Base:
    def greet(self): return ["Base"]
class Left(Base):
    def greet(self): return ["Left"] + super().greet()
class Right(Base):
    def greet(self): return ["Right"] + super().greet()
class Child(Left, Right):
    def greet(self): return ["Child"] + super().greet()

print([c.__name__ for c in Child.__mro__])
print(Child().greet())
print(Left().greet())

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • MRO uses C3 linearisation
  • super() follows the instance's MRO
  • Each class appears once
  • Cooperative classes all call super()
  • Bases order matters

Common mistakes

  • Calling Parent.method(self) directly in diamond hierarchies
  • Assuming super() means the parent

Follow-ups

  • When does C3 linearisation fail?
  • What are mixins?

Tips

  • Print __mro__ first
45.python-0045Mediummid

How do abstract base classes and Protocols define interfaces in Python?

abc.ABC with @abstractmethod defines a base class that cannot be instantiated until subclasses implement the abstract methods, enforcing the interface at runtime. typing.Protocol describes an interface structurally: any class with matching methods satisfies it for type checkers, without inheriting, which fits duck typing.

Full answer
python
from abc import ABC, abstractmethod
from typing import Protocol, runtime_checkable

class Notifier(ABC):
    @abstractmethod
    def send(self, to: str, msg: str) -> str: ...

class Email(Notifier):
    def send(self, to, msg): return f"email to {to}: {msg}"

class Broken(Notifier):
    pass

print(Email().send("asha@x.com", "hi"))
try:
    Broken()
except TypeError as e:
    print("TypeError:", e)

@runtime_checkable
class Sender(Protocol):
    def send(self, to: str, msg: str) -> str: ...

class Sms:
    def send(self, to, msg): return f"sms to {to}: {msg}"
print(isinstance(Sms(), Sender), isinstance(Sms(), Notifier))

Output:

text
email to asha@x.com: hi
TypeError: Can't instantiate abstract class Broken without an implementation for abstract method 'send'
True False

Instantiating Broken fails because it does not implement send; the error lists the missing method. Sms never inherits from anything, yet it satisfies the Sender protocol, and runtime_checkable allows an isinstance check that only verifies the method exists, not its signature. It is not a Notifier because ABCs require inheritance or registration. Use ABCs when you own the hierarchy and want shared code; use Protocols to type code that accepts any object with the right methods.

python
from abc import ABC, abstractmethod
from typing import Protocol, runtime_checkable

class Notifier(ABC):
    @abstractmethod
    def send(self, to: str, msg: str) -> str: ...

class Email(Notifier):
    def send(self, to, msg): return f"email to {to}: {msg}"

class Broken(Notifier):
    pass

print(Email().send("asha@x.com", "hi"))
try:
    Broken()
except TypeError as e:
    print("TypeError:", e)

@runtime_checkable
class Sender(Protocol):
    def send(self, to: str, msg: str) -> str: ...

class Sms:
    def send(self, to, msg): return f"sms to {to}: {msg}"
print(isinstance(Sms(), Sender), isinstance(Sms(), Notifier))

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • ABCs enforce abstract methods at instantiation
  • Protocols are structural
  • runtime_checkable checks method presence only
  • ABCs can share implementation
  • Protocols fit duck typing

Common mistakes

  • Expecting Protocols to be enforced at runtime by default
  • Deep ABC hierarchies for simple interfaces

Follow-ups

  • How does ABC.register work?
  • When would a Protocol be generic?

Tips

  • Contrast nominal and structural typing
46.python-0046Mediummid

Use Enum for fixed sets of values and show its common features.

Enum creates a set of named, unique constants. Members compare by identity, can be looked up by value or name, and can be iterated. StrEnum and IntEnum members also behave like strings or integers, which helps with JSON and databases; auto() assigns values automatically.

Full answer
python
from enum import Enum, StrEnum, auto

class Status(StrEnum):
    PENDING = auto()
    SHIPPED = auto()
    CANCELLED = auto()

class Size(Enum):
    S = 1
    M = 2
    L = 3

print(Status.SHIPPED, Status("pending"), Status["CANCELLED"].value)
print(Status.SHIPPED == "shipped", [s.value for s in Status])
print(Size(2), Size.M.name, Size.M is Size(2), Size.M == 2)
try:
    Status("lost")
except ValueError as e:
    print("ValueError:", e)
match Status("shipped"):
    case Status.SHIPPED:
        print("track parcel")

Output:

text
shipped pending cancelled
True ['pending', 'shipped', 'cancelled']
Size.M M True False
ValueError: 'lost' is not a valid Status
track parcel

With StrEnum, auto() produces lowercase names as values, and members compare equal to plain strings, so Status.SHIPPED == 'shipped' is True. Plain Enum members are not equal to their values (Size.M == 2 is False), which prevents accidental mixing. Looking up an unknown value raises ValueError, a cheap way to validate input. Enums work well with match statements. Store .value in databases and JSON, and convert back with Status(value).

python
from enum import Enum, StrEnum, auto

class Status(StrEnum):
    PENDING = auto()
    SHIPPED = auto()
    CANCELLED = auto()

class Size(Enum):
    S = 1
    M = 2
    L = 3

print(Status.SHIPPED, Status("pending"), Status["CANCELLED"].value)
print(Status.SHIPPED == "shipped", [s.value for s in Status])
print(Size(2), Size.M.name, Size.M is Size(2), Size.M == 2)
try:
    Status("lost")
except ValueError as e:
    print("ValueError:", e)
match Status("shipped"):
    case Status.SHIPPED:
        print("track parcel")

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Enums give named unique constants
  • Lookup by value or name
  • StrEnum and IntEnum mix in base types
  • Unknown values raise ValueError
  • Store .value externally

Common mistakes

  • Using bare strings for statuses everywhere
  • Comparing plain Enum members with raw values

Follow-ups

  • What does @enum.unique do?
  • How would you add a method to an Enum?

Tips

  • Show validation by lookup
47.python-0047Mediummid

How should logging be set up instead of print statements?

Create a logger per module with logging.getLogger(__name__), configure handlers and levels once at the application entry point, and log with lazy %-style arguments. Use levels (DEBUG to CRITICAL) to filter output and logger.exception inside except blocks to include tracebacks.

Full answer
python
import logging, sys
logging.basicConfig(stream=sys.stdout, level=logging.INFO,
                    format="%(levelname)s %(name)s: %(message)s")
log = logging.getLogger("shop.orders")

def place(order_id, qty):
    log.debug("validating %s", order_id)
    if qty <= 0:
        log.warning("rejected order %s: qty=%s", order_id, qty)
        return False
    try:
        1 / 0
    except ZeroDivisionError:
        log.exception("failed to price order %s", order_id)
    log.info("placed order %s", order_id)
    return True

place(7, 0)
place(8, 2)
logging.getLogger("shop").setLevel(logging.ERROR)
place(9, 0)
print("done")

Output:

text
WARNING shop.orders: rejected order 7: qty=0
ERROR shop.orders: failed to price order 8
Traceback (most recent call last):
  File "<stdin>", line 12, in place
ZeroDivisionError: division by zero
INFO shop.orders: placed order 8
done

The DEBUG message is not shown because the level is INFO. log.exception logs at ERROR and appends the traceback. Setting the parent logger 'shop' to ERROR silences the warning for order 9, because child loggers inherit their effective level. Passing arguments instead of f-strings defers formatting until a handler actually emits the record. Libraries should never call basicConfig; only the application configures handlers, often with JSON formatters for log aggregation.

python
import logging, sys
logging.basicConfig(stream=sys.stdout, level=logging.INFO,
                    format="%(levelname)s %(name)s: %(message)s")
log = logging.getLogger("shop.orders")

def place(order_id, qty):
    log.debug("validating %s", order_id)
    if qty <= 0:
        log.warning("rejected order %s: qty=%s", order_id, qty)
        return False
    try:
        1 / 0
    except ZeroDivisionError:
        log.exception("failed to price order %s", order_id)
    log.info("placed order %s", order_id)
    return True

place(7, 0)
place(8, 2)
logging.getLogger("shop").setLevel(logging.ERROR)
place(9, 0)
print("done")

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • One logger per module via __name__
  • Configure once at the entry point
  • Levels filter messages
  • logger.exception adds tracebacks
  • Lazy formatting with arguments

Common mistakes

  • Calling basicConfig in library code
  • Using print for operational logs

Follow-ups

  • How would you log JSON for a log aggregator?
  • How do logger hierarchies work?

Tips

  • Show level filtering
48.python-0048Mediummid

Write unit tests for a discount function with unittest, and show the pytest equivalent with fixtures and parametrisation.

unittest (standard library) groups tests in TestCase classes with assert methods and subTest for parametrised cases. pytest, the more common third-party runner, uses plain assert, fixtures injected by parameter name and @pytest.mark.parametrize. Good unit tests are fast, isolated, deterministic and check one behaviour each.

Full answer
python
import io, unittest

def apply_discount(price, pct):
    if not 0 <= pct <= 100:
        raise ValueError("pct out of range")
    return round(price * (100 - pct) / 100, 2)

class DiscountTests(unittest.TestCase):
    def setUp(self):
        self.cart = {"pen": 10.0, "bag": 250.0}
    def test_discount(self):
        for price, pct, expected in [(100, 10, 90.0), (99.99, 0, 99.99), (50, 100, 0.0)]:
            with self.subTest(price=price, pct=pct):
                self.assertEqual(apply_discount(price, pct), expected)
    def test_rejects_bad_pct(self):
        with self.assertRaisesRegex(ValueError, "out of range"):
            apply_discount(10, 120)
    def test_cart_total(self):
        self.assertEqual(sum(apply_discount(p, 10) for p in self.cart.values()), 234.0)

stream = io.StringIO()
result = unittest.TextTestRunner(stream=stream, verbosity=0).run(unittest.defaultTestLoader.loadTestsFromTestCase(DiscountTests))
print("ran", result.testsRun, "tests, ok =", result.wasSuccessful())

Output:

text
ran 3 tests, ok = True

The unittest version runs in the standard library: subTest reports each input separately, assertRaisesRegex checks the exception type and message, and setUp plays the role of a fixture. The run prints only the result line, without timing, so the output is stable.

The same tests in pytest style (pytest is not installed on this box, so this block was not run here):

python
@pytest.fixture
def cart():
    return {"pen": 10.0, "bag": 250.0}

@pytest.mark.parametrize("price,pct,expected", [(100, 10, 90.0), (99.99, 0, 99.99), (50, 100, 0.0)])
def test_discount(price, pct, expected):
    assert apply_discount(price, pct) == expected

def test_rejects_bad_pct():
    with pytest.raises(ValueError, match="out of range"):
        apply_discount(10, 120)

Keep tests independent of order and of the network, use temporary directories for files, and mock only at boundaries such as HTTP clients.

python
import io, unittest

def apply_discount(price, pct):
    if not 0 <= pct <= 100:
        raise ValueError("pct out of range")
    return round(price * (100 - pct) / 100, 2)

class DiscountTests(unittest.TestCase):
    def setUp(self):
        self.cart = {"pen": 10.0, "bag": 250.0}
    def test_discount(self):
        for price, pct, expected in [(100, 10, 90.0), (99.99, 0, 99.99), (50, 100, 0.0)]:
            with self.subTest(price=price, pct=pct):
                self.assertEqual(apply_discount(price, pct), expected)
    def test_rejects_bad_pct(self):
        with self.assertRaisesRegex(ValueError, "out of range"):
            apply_discount(10, 120)
    def test_cart_total(self):
        self.assertEqual(sum(apply_discount(p, 10) for p in self.cart.values()), 234.0)

stream = io.StringIO()
result = unittest.TextTestRunner(stream=stream, verbosity=0).run(unittest.defaultTestLoader.loadTestsFromTestCase(DiscountTests))
print("ran", result.testsRun, "tests, ok =", result.wasSuccessful())

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • unittest is built in; pytest is the common runner
  • Parametrise with subTest or parametrize
  • Check exception type and message
  • Fixtures or setUp provide shared setup
  • Fast, isolated, deterministic tests

Common mistakes

  • Tests that depend on each other's order
  • Mocking the code under test

Follow-ups

  • How do pytest fixture scopes work?
  • When would you use monkeypatch or unittest.mock.patch?

Tips

  • Show parametrised cases
49.python-0049Mediummid

Use regular expressions to extract and validate data, and explain greedy versus lazy matching.

re.search finds the first match anywhere, re.fullmatch requires the whole string to match, and findall or finditer return all matches, with named groups keeping results readable. Quantifiers are greedy by default and match as much as possible; adding ? makes them lazy. Compile patterns used repeatedly and prefer raw strings.

Full answer
python
import re
log = "2026-12-04 10:15 ERROR order=104 user=asha; 2026-12-04 10:20 INFO order=105 user=ben"
pat = re.compile(r"(?P<time>\d{2}:\d{2}) (?P<level>[A-Z]+) order=(?P<order>\d+)")
print([m.groupdict() for m in pat.finditer(log)])
html = "<b>bold</b><i>it</i>"
print(re.findall(r"<.+>", html), re.findall(r"<.+?>", html))
pin = re.compile(r"[1-9]\d{5}")
print(bool(pin.search("PIN 4110016")), bool(pin.fullmatch("4110016")), bool(pin.fullmatch("411001")))
print(re.sub(r"\s+", " ", "too    many   spaces"))

Output:

text
[{'time': '10:15', 'level': 'ERROR', 'order': '104'}, {'time': '10:20', 'level': 'INFO', 'order': '105'}]
['<b>bold</b><i>it</i>'] ['<b>', '</b>', '<i>', '</i>']
True False True
too many spaces

Named groups give dictionaries per match, which is clearer than numbered groups. The greedy <.+> swallows the whole string from the first < to the last >, while the lazy <.+?> stops at each tag. search finds a six-digit run inside the seven-digit text, but fullmatch rejects it, which is why validation should use fullmatch (or anchors). Regex is good for structured text such as logs; for HTML or JSON, use a real parser.

python
import re
log = "2026-12-04 10:15 ERROR order=104 user=asha; 2026-12-04 10:20 INFO order=105 user=ben"
pat = re.compile(r"(?P<time>\d{2}:\d{2}) (?P<level>[A-Z]+) order=(?P<order>\d+)")
print([m.groupdict() for m in pat.finditer(log)])
html = "<b>bold</b><i>it</i>"
print(re.findall(r"<.+>", html), re.findall(r"<.+?>", html))
pin = re.compile(r"[1-9]\d{5}")
print(bool(pin.search("PIN 4110016")), bool(pin.fullmatch("4110016")), bool(pin.fullmatch("411001")))
print(re.sub(r"\s+", " ", "too    many   spaces"))

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • search, fullmatch, findall, finditer
  • Named groups improve readability
  • Greedy versus lazy quantifiers
  • Use fullmatch for validation
  • Use parsers for HTML and JSON

Common mistakes

  • Validating with search and partial matches
  • Parsing HTML with regex

Follow-ups

  • How would you match an email address reasonably?
  • What does re.VERBOSE allow?

Tips

  • Show greedy and lazy side by side
50.python-0050Mediummid

Work with dates, times and time zones correctly using datetime and zoneinfo.

Use timezone-aware datetimes for real instants: datetime.now(timezone.utc) or attach a ZoneInfo such as 'Asia/Kolkata'. Store and compute in UTC and convert to local time for display with astimezone. Naive datetimes have no zone, and mixing naive and aware values raises TypeError.

Full answer
python
from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo
ist = ZoneInfo("Asia/Kolkata"); london = ZoneInfo("Europe/London")
meeting = datetime(2026, 3, 28, 15, 0, tzinfo=ist)
print(meeting.isoformat(), meeting.astimezone(timezone.utc).isoformat())
print(meeting.astimezone(london).strftime("%H:%M %Z"), (meeting + timedelta(days=2)).astimezone(london).strftime("%H:%M %Z"))
naive = datetime(2026, 3, 28, 15, 0)
try:
    naive < meeting
except TypeError as e:
    print("TypeError:", e)
print(datetime.fromisoformat("2026-12-04T01:38:00+05:30").astimezone(timezone.utc))

Output:

text
2026-03-28T15:00:00+05:30 2026-03-28T09:30:00+00:00
09:30 GMT 10:30 BST
TypeError: can't compare offset-naive and offset-aware datetimes
2026-12-03 20:08:00+00:00

The 15:00 IST meeting is 09:30 UTC. In London it is 09:30 GMT on 28 March, but the same IST time two days later is 10:30 BST because the UK moved its clocks on 29 March 2026; ZoneInfo applies the rules automatically, while a fixed offset would be wrong. Comparing a naive and an aware datetime raises TypeError, which prevents silent mistakes. fromisoformat parses offsets, and converting to UTC normalises values for storage.

python
from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo
ist = ZoneInfo("Asia/Kolkata"); london = ZoneInfo("Europe/London")
meeting = datetime(2026, 3, 28, 15, 0, tzinfo=ist)
print(meeting.isoformat(), meeting.astimezone(timezone.utc).isoformat())
print(meeting.astimezone(london).strftime("%H:%M %Z"), (meeting + timedelta(days=2)).astimezone(london).strftime("%H:%M %Z"))
naive = datetime(2026, 3, 28, 15, 0)
try:
    naive < meeting
except TypeError as e:
    print("TypeError:", e)
print(datetime.fromisoformat("2026-12-04T01:38:00+05:30").astimezone(timezone.utc))

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Use aware datetimes for instants
  • Store UTC, display local
  • ZoneInfo handles daylight saving
  • Naive and aware values cannot be compared
  • fromisoformat parses offsets

Common mistakes

  • Using naive datetime.now() for timestamps
  • Hard-coding UTC offsets for zones with DST

Follow-ups

  • How would you schedule a daily 9 AM job in a user's zone?
  • What is the fold attribute for?

Tips

  • Show the DST change
51.python-0051Mediummid

What is the walrus operator (:=), and where does it make code clearer?

The assignment expression name := value assigns and returns a value inside an expression. It avoids computing something twice in a condition, reading in a while loop, or repeating a call in a comprehension filter. Use it where it shortens code without hiding logic.

Full answer
python
import re
data = iter(["10", "20", "", "30"])
total = 0
while (line := next(data)) != "":
    total += int(line)
print(total)

codes = ["A-12", "bad", "B-7"]
print([int(m.group(1)) for c in codes if (m := re.fullmatch(r"[A-Z]-(\d+)", c))])

def expensive(x):
    print("computing", x)
    return x * x
values = [1, 5, 3]
print([y for x in values if (y := expensive(x)) > 5])

Output:

text
30
[12, 7]
computing 1
computing 5
computing 3
[25, 9]

The loop reads values until an empty string appears, without a separate read before the loop and another at the end. In the comprehension, the regex match is stored in m and reused, instead of matching twice. The last example calls expensive once per item while both filtering and returning the result. Overuse makes code dense; avoid nesting several walruses or using them where a normal assignment on its own line reads better.

python
import re
data = iter(["10", "20", "", "30"])
total = 0
while (line := next(data)) != "":
    total += int(line)
print(total)

codes = ["A-12", "bad", "B-7"]
print([int(m.group(1)) for c in codes if (m := re.fullmatch(r"[A-Z]-(\d+)", c))])

def expensive(x):
    print("computing", x)
    return x * x
values = [1, 5, 3]
print([y for x in values if (y := expensive(x)) > 5])

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Assigns inside expressions
  • Avoids repeated computation
  • Useful in while loops and filters
  • Keep usage simple

Common mistakes

  • Using := where plain assignment is clearer
  • Forgetting parentheses around the walrus in conditions

Follow-ups

  • What scope does a walrus target in a comprehension have?
  • Which Python version added it?

Tips

  • Show the repeated-computation case
52.python-0052Mediummid

How does structural pattern matching (match/case) work beyond simple value checks?

match compares a subject against case patterns that can test literals, sequences, mappings, class shapes and types, binding variables from the matched parts. Guards with if add conditions, | combines alternatives, and _ is the wildcard. It shines when handling structured data such as parsed commands or JSON events.

Full answer
python
from dataclasses import dataclass
@dataclass
class Point:
    x: int
    y: int

def describe(event):
    match event:
        case {"type": "click", "pos": [x, y]} if x < 0 or y < 0:
            return "click off-screen"
        case {"type": "click", "pos": [x, y]}:
            return f"click at {x},{y}"
        case {"type": "key", "key": "q" | "Q"}:
            return "quit"
        case Point(x=0, y=0):
            return "origin"
        case Point(x=x, y=y):
            return f"point {x},{y}"
        case [first, *rest]:
            return f"list starting {first}, {len(rest)} more"
        case _:
            return "unknown"

for e in [{"type": "click", "pos": [3, 4]}, {"type": "click", "pos": [-1, 2]}, {"type": "key", "key": "Q", "extra": 1},
          Point(0, 0), Point(2, 5), [1, 2, 3], "hello"]:
    print(describe(e))

Output:

text
click at 3,4
click off-screen
quit
origin
point 2,5
list starting 1, 2 more
unknown

Cases are tried in order, so the guarded off-screen case comes before the general click case. Mapping patterns match if the listed keys exist, ignoring extra keys such as 'extra'. Class patterns check the type and attributes, and sequence patterns destructure lists with *rest. A plain string does not match the sequence pattern, because strings are deliberately excluded from sequence patterns, so it falls through to _. Remember that a bare name in a case captures rather than compares; use dotted names or literals for constants.

python
from dataclasses import dataclass
@dataclass
class Point:
    x: int
    y: int

def describe(event):
    match event:
        case {"type": "click", "pos": [x, y]} if x < 0 or y < 0:
            return "click off-screen"
        case {"type": "click", "pos": [x, y]}:
            return f"click at {x},{y}"
        case {"type": "key", "key": "q" | "Q"}:
            return "quit"
        case Point(x=0, y=0):
            return "origin"
        case Point(x=x, y=y):
            return f"point {x},{y}"
        case [first, *rest]:
            return f"list starting {first}, {len(rest)} more"
        case _:
            return "unknown"

for e in [{"type": "click", "pos": [3, 4]}, {"type": "click", "pos": [-1, 2]}, {"type": "key", "key": "Q", "extra": 1},
          Point(0, 0), Point(2, 5), [1, 2, 3], "hello"]:
    print(describe(e))

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Patterns match shapes and bind names
  • Cases run in order
  • Guards add conditions
  • Mapping patterns ignore extra keys
  • Bare names capture, dotted names compare

Common mistakes

  • Writing case STATUS: expecting a comparison
  • Putting general cases before specific ones

Follow-ups

  • How does __match_args__ work?
  • When is a dict of handlers simpler than match?

Tips

  • Order cases from specific to general
53.python-0053Mediummid

Explain the defaultdict, Counter, deque and namedtuple tools in collections with a realistic task.

defaultdict creates missing values automatically, Counter counts hashable items and supports arithmetic, deque gives O(1) appends and pops at both ends with an optional maxlen for sliding windows, and namedtuple creates lightweight immutable records with named fields.

Full answer
python
from collections import defaultdict, Counter, deque, namedtuple
Visit = namedtuple("Visit", "user page")
visits = [Visit("asha", "/home"), Visit("ben", "/cart"), Visit("asha", "/cart"), Visit("asha", "/home")]
pages_by_user = defaultdict(set)
for v in visits:
    pages_by_user[v.user].add(v.page)
print({u: sorted(p) for u, p in pages_by_user.items()})
hits = Counter(v.page for v in visits)
print(hits.most_common(1), hits - Counter({"/home": 1}))
recent = deque(maxlen=2)
for v in visits:
    recent.append(v.page)
print(list(recent), visits[0]._replace(page="/about"))

Output:

text
{'asha': ['/cart', '/home'], 'ben': ['/cart']}
[('/home', 2)] Counter({'/cart': 2, '/home': 1})
['/cart', '/home'] Visit(user='asha', page='/about')

defaultdict(set) removes the 'if key not in dict' boilerplate while grouping pages per user. Counter finds the most visited page and subtracts counts, dropping keys that reach zero or below. deque(maxlen=2) keeps only the two most recent pages, discarding older ones automatically, which is a sliding window. The namedtuple gives readable field access and _replace returns a modified copy.

python
from collections import defaultdict, Counter, deque, namedtuple
Visit = namedtuple("Visit", "user page")
visits = [Visit("asha", "/home"), Visit("ben", "/cart"), Visit("asha", "/cart"), Visit("asha", "/home")]
pages_by_user = defaultdict(set)
for v in visits:
    pages_by_user[v.user].add(v.page)
print({u: sorted(p) for u, p in pages_by_user.items()})
hits = Counter(v.page for v in visits)
print(hits.most_common(1), hits - Counter({"/home": 1}))
recent = deque(maxlen=2)
for v in visits:
    recent.append(v.page)
print(list(recent), visits[0]._replace(page="/about"))

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • defaultdict for grouping
  • Counter for counting and ranking
  • deque(maxlen) for sliding windows
  • namedtuple for light records

Common mistakes

  • Using list.pop(0) for queues
  • Accidentally creating keys by reading a defaultdict

Follow-ups

  • When would a dataclass replace namedtuple?
  • How does Counter handle negative counts?

Tips

  • Pick a tool per sub-task
54.python-0054Mediummid

Why do closures in a loop capture the last value, and how do you fix it?

Closures look up free variables when they are called, not when they are created, so functions created in a loop all see the loop variable's final value. Bind the current value at creation with a default argument, functools.partial or a factory function.

Full answer
python
from functools import partial
handlers = []
for name in ["save", "load", "quit"]:
    handlers.append(lambda: f"clicked {name}")
print([h() for h in handlers])

fixed = [lambda name=name: f"clicked {name}" for name in ["save", "load", "quit"]]
print([h() for h in fixed])

def make_handler(name):
    return lambda: f"clicked {name}"
print([make_handler(n)() for n in ["save", "load"]])
print([partial(str.format, "clicked {}", n)() for n in ["save", "load"]])

Output:

text
['clicked quit', 'clicked quit', 'clicked quit']
['clicked save', 'clicked load', 'clicked quit']
['clicked save', 'clicked load']
['clicked save', 'clicked load']

All three buttons report 'quit' because each lambda refers to the same variable name, which ends the loop as 'quit'. The default-argument version evaluates name when each lambda is defined. A factory function creates a new scope per call, so each closure gets its own name. partial stores the argument value directly. This bug appears in GUI callbacks, scheduled tasks and dictionaries of handlers.

python
from functools import partial
handlers = []
for name in ["save", "load", "quit"]:
    handlers.append(lambda: f"clicked {name}")
print([h() for h in handlers])

fixed = [lambda name=name: f"clicked {name}" for name in ["save", "load", "quit"]]
print([h() for h in fixed])

def make_handler(name):
    return lambda: f"clicked {name}"
print([make_handler(n)() for n in ["save", "load"]])
print([partial(str.format, "clicked {}", n)() for n in ["save", "load"]])

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Closures bind variables, not values
  • Lookup happens at call time
  • Default arguments capture values
  • Factory functions create new scopes
  • partial stores arguments

Common mistakes

  • Creating callbacks in loops without binding
  • Assuming each iteration gets a new variable

Follow-ups

  • How does this differ in JavaScript with let?
  • Can the default-argument fix be misused by callers?

Tips

  • Explain call-time lookup
55.python-0055Mediummid

When should you use @classmethod and @staticmethod?

A classmethod receives the class as cls and is the standard way to write alternative constructors that also work for subclasses. A staticmethod receives neither the instance nor the class and is just a function placed in the class namespace for organisation. Regular methods receive the instance.

Full answer
python
from datetime import date
class Student:
    def __init__(self, name, born):
        self.name, self.born = name, born
    @classmethod
    def from_csv(cls, line):
        name, year = line.split(",")
        return cls(name.strip(), date(int(year), 1, 1))
    @staticmethod
    def is_valid_name(name):
        return name.replace(" ", "").isalpha()
    def __repr__(self):
        return f"{type(self).__name__}({self.name!r}, {self.born.year})"

class Intern(Student):
    pass

print(Student.from_csv("Asha Rao, 2004"), Intern.from_csv("Ben, 2006"))
print(Student.is_valid_name("Asha Rao"), Student.is_valid_name("R2D2"))

Output:

text
Student('Asha Rao', 2004) Intern('Ben', 2006)
True False

Intern.from_csv returns an Intern, because cls is whichever class the method was called on; a staticmethod that hard-coded Student(...) would lose that. is_valid_name needs no instance or class data, so it is a staticmethod; a module-level function would work equally well. Familiar library examples are dict.fromkeys and datetime.fromisoformat, both classmethods. Choose a regular method whenever the code needs instance data, a classmethod when it needs the class, and a staticmethod only for helpers that belong with the class conceptually.

python
from datetime import date
class Student:
    def __init__(self, name, born):
        self.name, self.born = name, born
    @classmethod
    def from_csv(cls, line):
        name, year = line.split(",")
        return cls(name.strip(), date(int(year), 1, 1))
    @staticmethod
    def is_valid_name(name):
        return name.replace(" ", "").isalpha()
    def __repr__(self):
        return f"{type(self).__name__}({self.name!r}, {self.born.year})"

class Intern(Student):
    pass

print(Student.from_csv("Asha Rao, 2004"), Intern.from_csv("Ben, 2006"))
print(Student.is_valid_name("Asha Rao"), Student.is_valid_name("R2D2"))

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • classmethod receives cls
  • Alternative constructors use classmethod
  • Subclasses get the right type
  • staticmethod is a namespaced function
  • Module functions are often as good

Common mistakes

  • Hard-coding the class name in factories
  • Using staticmethod for code that needs class data

Follow-ups

  • How would you register subclasses automatically?
  • What does __init_subclass__ do?

Tips

  • Show the subclass factory
56.python-0056Mediummid

How do you profile slow Python code and find the hot spot?

Measure before optimising: use timeit for small snippets, cProfile to see which functions take the most cumulative time, and line profilers or py-spy for finer detail. Then fix the hot spot, often an algorithm or data-structure choice such as a list membership test inside a loop, and measure again.

Full answer
python
import cProfile, pstats, io

def slow_unique(items):
    seen = []
    for x in items:
        if x not in seen:
            seen.append(x)
    return seen

def fast_unique(items):
    return list(dict.fromkeys(items))

data = list(range(3000)) * 2
pr = cProfile.Profile()
pr.enable(); slow_unique(data); fast_unique(data); pr.disable()
stats = pstats.Stats(pr).sort_stats("cumulative")
rows = sorted(((v[3], k[2]) for k, v in stats.stats.items() if k[2] in ("slow_unique", "fast_unique")), reverse=True)
print("slowest first:", [name for _, name in rows])
print(slow_unique(data) == fast_unique(data))

Output:

text
slowest first: ['slow_unique', 'fast_unique']
True

The profiler records cumulative time per function; the run prints only the ranking, not timings, so the result is stable. slow_unique dominates because x not in seen scans a growing list, making the function quadratic, while dict.fromkeys uses hashing and is linear. Both produce the same result, so the fix is safe. In real services, profile with production-like data, look at cumulative time first, and consider I/O waits, which profilers attribute to waiting functions rather than computation.

python
import cProfile, pstats, io

def slow_unique(items):
    seen = []
    for x in items:
        if x not in seen:
            seen.append(x)
    return seen

def fast_unique(items):
    return list(dict.fromkeys(items))

data = list(range(3000)) * 2
pr = cProfile.Profile()
pr.enable(); slow_unique(data); fast_unique(data); pr.disable()
stats = pstats.Stats(pr).sort_stats("cumulative")
rows = sorted(((v[3], k[2]) for k, v in stats.stats.items() if k[2] in ("slow_unique", "fast_unique")), reverse=True)
print("slowest first:", [name for _, name in rows])
print(slow_unique(data) == fast_unique(data))

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Measure first
  • timeit for snippets, cProfile for programs
  • Sort by cumulative time
  • Fix algorithms before micro-optimising
  • Verify results stay the same

Common mistakes

  • Optimising without profiling
  • Micro-optimising code that is not the bottleneck

Follow-ups

  • How does py-spy profile a running process?
  • When does tracemalloc help?

Tips

  • Show the before and after
57.python-0057Mediummid

Explain virtual environments and dependency management for a Python project.

A virtual environment is an isolated directory with its own interpreter link and site-packages, so each project has its own dependency versions. Create one with python -m venv .venv, install with pip inside it, and record dependencies in pyproject.toml with a lock file (or a pinned requirements file) for reproducible installs.

Full answer
python
import os, subprocess, sys, tempfile
d = tempfile.mkdtemp()
env = os.path.join(d, ".venv")
subprocess.run([sys.executable, "-m", "venv", "--without-pip", env], check=True)
py = os.path.join(env, "bin", "python")
out = subprocess.run([py, "-c", "import sys; print(sys.prefix != sys.base_prefix, sys.version_info[:2])"],
                     capture_output=True, text=True).stdout.strip()
print(out)
print(sorted(os.listdir(env)))

Output:

text
True (3, 13)
['.gitignore', 'bin', 'include', 'lib', 'lib64', 'pyvenv.cfg']

The run creates a virtual environment (without pip, to keep it offline and quick) and checks from inside it that sys.prefix differs from sys.base_prefix, which is how code detects a venv. The directory contains bin, include, lib (plus a lib64 link on this system), pyvenv.cfg, and, since Python 3.13, a .gitignore that keeps the environment out of version control. Good practice: never install project packages into the system Python, commit pyproject.toml and a lock file, not the .venv folder, and separate development tools (pytest, linters) from runtime dependencies. Tools like uv or Poetry automate environments and locking; pip with requirements.txt remains common.

python
import os, subprocess, sys, tempfile
d = tempfile.mkdtemp()
env = os.path.join(d, ".venv")
subprocess.run([sys.executable, "-m", "venv", "--without-pip", env], check=True)
py = os.path.join(env, "bin", "python")
out = subprocess.run([py, "-c", "import sys; print(sys.prefix != sys.base_prefix, sys.version_info[:2])"],
                     capture_output=True, text=True).stdout.strip()
print(out)
print(sorted(os.listdir(env)))

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • venv isolates dependencies per project
  • sys.prefix shows the active environment
  • Declare dependencies in pyproject.toml
  • Lock exact versions for reproducibility
  • Do not commit the venv

Common mistakes

  • Installing everything globally
  • Unpinned dependencies in production

Follow-ups

  • What is the difference between a library's and an application's dependency pins?
  • How does uv speed up installs?

Tips

  • Mention lock files
58.python-0058Mediummid

Read and write CSV files correctly, including quoting and dictionaries.

Use the csv module rather than splitting on commas, because fields may contain commas, quotes or newlines. Open files with newline='' and an explicit encoding. DictReader and DictWriter map rows to dictionaries keyed by the header, which keeps code readable when columns change order.

Full answer
python
import csv, io
buf = io.StringIO(newline="")
w = csv.DictWriter(buf, fieldnames=["name", "city", "note"])
w.writeheader()
w.writerow({"name": "Asha", "city": "Pune", "note": "likes SQL, Python"})
w.writerow({"name": "Ben", "city": "Leeds", "note": 'said "hi"'})
text = buf.getvalue()
print(text)
rows = list(csv.DictReader(io.StringIO(text, newline="")))
print(rows[0]["note"], "|", rows[1]["note"])
print(text.splitlines()[1].split(","))

Output:

text
name,city,note
Asha,Pune,"likes SQL, Python"
Ben,Leeds,"said ""hi"""

likes SQL, Python | said "hi"
['Asha', 'Pune', '"likes SQL', ' Python"']

The writer quoted the note containing a comma and doubled the quotes inside Ben's note, following the CSV rules. Reading back with DictReader restores the original values exactly. The last line shows why naive splitting fails: it breaks Asha's note into two fields. With real files, open(path, newline='', encoding='utf-8') avoids blank lines on Windows and encoding surprises. For large data analysis, pandas or DuckDB read CSV faster, but the csv module is dependable for streaming rows.

python
import csv, io
buf = io.StringIO(newline="")
w = csv.DictWriter(buf, fieldnames=["name", "city", "note"])
w.writeheader()
w.writerow({"name": "Asha", "city": "Pune", "note": "likes SQL, Python"})
w.writerow({"name": "Ben", "city": "Leeds", "note": 'said "hi"'})
text = buf.getvalue()
print(text)
rows = list(csv.DictReader(io.StringIO(text, newline="")))
print(rows[0]["note"], "|", rows[1]["note"])
print(text.splitlines()[1].split(","))

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Use the csv module, not split
  • newline='' and explicit encoding
  • DictReader and DictWriter use headers
  • Quoting handles commas and quotes

Common mistakes

  • Splitting lines on commas
  • Opening CSV files without newline=''

Follow-ups

  • How would you process a CSV larger than memory?
  • How do you handle different delimiters?

Tips

  • Show the failing split
59.python-0059Hardsenior

How do descriptors work, and how do property and methods rely on them?

A descriptor is an object defining __get__, and optionally __set__ or __delete__, stored as a class attribute; attribute access on instances then calls those methods. Data descriptors (with __set__) take priority over the instance dictionary, non-data descriptors do not. property, functions becoming bound methods, classmethod and staticmethod are all descriptors.

Full answer
python
class Positive:
    def __set_name__(self, owner, name):
        self.private = "_" + name
    def __get__(self, obj, objtype=None):
        if obj is None:
            return self
        return getattr(obj, self.private)
    def __set__(self, obj, value):
        if value <= 0:
            raise ValueError(f"{self.private[1:]} must be positive, got {value}")
        setattr(obj, self.private, value)

class Product:
    price = Positive()
    qty = Positive()
    def __init__(self, price, qty):
        self.price, self.qty = price, qty

p = Product(10, 3)
print(p.price * p.qty, vars(p))
try:
    p.qty = 0
except ValueError as e:
    print("ValueError:", e)
print(type(Product.__dict__["price"]).__name__, hasattr(Product.__init__, "__get__"))

Output:

text
30 {'_price': 10, '_qty': 3}
ValueError: qty must be positive, got 0
Positive True

__set_name__ (Python 3.6+) tells each descriptor its attribute name, so one Positive class validates both fields and stores values under _price and _qty, as vars(p) shows. Assigning 0 to qty goes through __set__ and is rejected. Accessing the attribute on the class returns the descriptor itself because obj is None. Plain functions have __get__, which is how p.method becomes a bound method with self filled in. Descriptors are how ORMs map columns to attributes.

python
class Positive:
    def __set_name__(self, owner, name):
        self.private = "_" + name
    def __get__(self, obj, objtype=None):
        if obj is None:
            return self
        return getattr(obj, self.private)
    def __set__(self, obj, value):
        if value <= 0:
            raise ValueError(f"{self.private[1:]} must be positive, got {value}")
        setattr(obj, self.private, value)

class Product:
    price = Positive()
    qty = Positive()
    def __init__(self, price, qty):
        self.price, self.qty = price, qty

p = Product(10, 3)
print(p.price * p.qty, vars(p))
try:
    p.qty = 0
except ValueError as e:
    print("ValueError:", e)
print(type(Product.__dict__["price"]).__name__, hasattr(Product.__init__, "__get__"))

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Descriptors define __get__/__set__ on class attributes
  • Data descriptors override instance dicts
  • __set_name__ gives the attribute name
  • Functions are non-data descriptors
  • property is a descriptor

Common mistakes

  • Storing the value under the same name and recursing
  • Storing per-instance values on the descriptor itself

Follow-ups

  • How does attribute lookup order work exactly?
  • How do ORMs use descriptors?

Tips

  • Store per-instance data on the instance
60.python-0060Hardsenior

What are metaclasses, and what simpler tools usually replace them?

A metaclass is the class of a class: type by default, and it controls how class objects are created. Custom metaclasses can register or validate classes at definition time. Most of those needs are met more simply by __init_subclass__ or class decorators, so metaclasses are rare in application code.

Full answer
python
class PluginMeta(type):
    registry = {}
    def __new__(mcls, name, bases, ns):
        cls = super().__new__(mcls, name, bases, ns)
        if bases:
            mcls.registry[ns.get("name", name.lower())] = cls
        return cls

class Plugin(metaclass=PluginMeta):
    pass
class CsvExport(Plugin):
    name = "csv"
class PdfExport(Plugin):
    pass
print(sorted(PluginMeta.registry), type(CsvExport).__name__, type(int).__name__)

class Handler:
    handlers = {}
    def __init_subclass__(cls, event, **kw):
        super().__init_subclass__(**kw)
        Handler.handlers[event] = cls
class OnSignup(Handler, event="signup"):
    pass
print(Handler.handlers)

Output:

text
['csv', 'pdfexport'] PluginMeta type
{'signup': <class '__main__.OnSignup'>}

The metaclass registers every subclass of Plugin when its class statement runs, keyed by a name attribute or the lowercased class name. type(CsvExport) is the metaclass, while ordinary classes such as int have type as their metaclass. The __init_subclass__ version achieves the same registration, even accepting a keyword argument in the class header, without a metaclass. Metaclasses also conflict when combining classes with different metaclasses, another reason to prefer the simpler hooks. Frameworks such as Django models and enum use them internally.

python
class PluginMeta(type):
    registry = {}
    def __new__(mcls, name, bases, ns):
        cls = super().__new__(mcls, name, bases, ns)
        if bases:
            mcls.registry[ns.get("name", name.lower())] = cls
        return cls

class Plugin(metaclass=PluginMeta):
    pass
class CsvExport(Plugin):
    name = "csv"
class PdfExport(Plugin):
    pass
print(sorted(PluginMeta.registry), type(CsvExport).__name__, type(int).__name__)

class Handler:
    handlers = {}
    def __init_subclass__(cls, event, **kw):
        super().__init_subclass__(**kw)
        Handler.handlers[event] = cls
class OnSignup(Handler, event="signup"):
    pass
print(Handler.handlers)

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Classes are instances of metaclasses
  • type is the default metaclass
  • Metaclasses hook class creation
  • __init_subclass__ covers most registration needs
  • Metaclass conflicts complicate inheritance

Common mistakes

  • Using metaclasses for simple validation
  • Mixing classes with incompatible metaclasses

Follow-ups

  • What does __prepare__ do?
  • How does enum use a metaclass?

Tips

  • Offer __init_subclass__ as the alternative