Interview Q&A · Python · 35 questions in this topic
Advanced Python — Python Interview Q&A
The internals interviewers probe on senior rounds — memory model, the GIL, slots, profiling, descriptors and the corners of the language standard guides skip. Part of Advanced Python · 375 questions in the Python bank.
How does Python manage memory, in more depth than the basics?
Answer
CPython uses reference counting as its primary memory management mechanism, backed by a generational cyclic garbage collector for reference cycles, and an internal memory allocator (pymalloc) that manages small-object memory in efficient pools rather than calling the operating system's allocator for every single object.
pymalloc exists because general-purpose OS memory allocation is relatively expensive, and Python programs typically create huge numbers of small, short-lived objects — a specialized allocator that manages pre-allocated pools of fixed-size memory blocks is dramatically faster for this specific workload pattern.
Example
import sys x = [] print(sys.getrefcount(x)) # baseline refcount (includes the temporary arg reference) y = x print(sys.getrefcount(x)) # incremented -- another name references the same object del y print(sys.getrefcount(x)) # decremented again
💡 Structuring the answer in three layers — reference counting (immediate, deterministic), cyclic GC (handles what refcounting can't), and pymalloc (performance optimization for small objects) — shows a complete mental model rather than just "Python has garbage collection."
What is reference counting, and how can you inspect an object's reference count?
Answer
Every object keeps a count of how many references point to it. When that count drops to zero, CPython deallocates the object immediately and deterministically. You can inspect it with sys.getrefcount(obj), though the returned value is always at least one higher than you'd naively expect.
sys.getrefcount() 's result includes the temporary reference created by passing the object into getrefcount() itself as an argument — so a "genuinely unreferenced" object still reports a count of 1, not 0, when checked this way.
Example
import sys a = [1, 2, 3] print(sys.getrefcount(a)) # e.g. 2 -- 'a' itself, plus the temporary arg to getrefcount() b = a print(sys.getrefcount(a)) # e.g. 3 -- 'a', 'b', plus the temporary arg del b print(sys.getrefcount(a)) # back to e.g. 2
💡 Mentioning that getrefcount() 's result is always inflated by one (due to its own argumentpassing) is a small correctness detail that shows you've actually used the function, not just read about it.
What causes reference cycles, and how does Python's cyclic garbage collector handle them?
Answer
A reference cycle occurs when two or more objects reference each other (directly or through a longer chain), so their reference counts never naturally reach zero even after nothing outside the cycle refers to them. Python's separate cyclic garbage collector periodically scans for and collects these otherwise-unreachable cycles.
The cyclic collector works by tracking "container" objects (those that can hold references to other objects, like lists, dicts, and class instances) and periodically checking whether groups of them are only reachable from within the group itself — such groups are true garbage, even though no individual object's reference count is technically zero.
Example
import gc class Node: def __init__(self, name): self.name = name self.partner = None a = Node("A") b = Node("B") a.partner = b # a references b b.partner = a # b references a -- a cycle! del a, b # neither object's refcount reaches zero -- they still reference each other collected = gc.collect() # manually trigger the cyclic collector print(f"Cyclic garbage collected: {collected} objects")
💡 A concrete example of why cycles happen in real code — parent/child object relationships, doubly linked lists, observer patterns with back-references — makes this answer much more convincing than the abstract a.partner = b demonstration alone.
What are "generations" in Python's garbage collector?
Answer
CPython's cyclic garbage collector groups objects into three generations (0, 1, 2) based on how long they've survived previous collection passes. Generation 0 (newest objects) is collected most frequently, while generation 2 (long-lived objects) is collected least often — based on the empirical observation that most objects die young.
This "generational hypothesis" (most objects are short-lived; objects that survive one collection are likely to survive many more) lets the collector focus most of its effort on the generation most likely to actually contain garbage, making garbage collection significantly more efficient than scanning every tracked object on every single pass.
Example
import gc print(gc.get_threshold()) # e.g. (700, 10, 10) -- collection thresholds per generation print(gc.get_count()) # current object counts in each generation # Objects that survive a generation-0 collection get "promoted" to generation 1, # and eventually to generation 2 if they keep surviving -- exactly like some # other generational garbage collectors (e.g., in the JVM).
💡 If you've used a JVM-based language before, drawing the direct parallel to Java's generational garbage collector is a great way to show transferable systems knowledge rather than treating this as Python-specific trivia.
How would you manually control garbage collection using the gc module?
Answer
The gc module lets you manually trigger a collection (gc.collect()), disable/enable automatic collection (gc.disable() / gc.enable()), inspect what's being tracked, and adjust collection thresholds — useful for performance tuning in specific, measured scenarios.
Disabling automatic garbage collection is a real (if situational) performance technique in latency-sensitive applications with predictable memory patterns — some high-performance services disable cyclic GC entirely, relying purely on reference counting, and only trigger manual collections during known idle periods.
Example
import gc gc.disable() # turn off automatic cyclic collection # ... performance-critical section that creates many short-lived objects ... gc.enable() # turn it back on gc.collect() # manually trigger a full collection right now print(gc.isenabled()) # check current status
What are Python namespaces, and how do they relate to scope?
Answer
A namespace is a mapping from names to objects — essentially a dictionary Python uses internally to track what names exist and what they refer to at a given level (module, function, class). Scope (LEGB, from describes the rules for which namespace Python searches, and in what order, when resolving a name.
Namespaces are concrete, inspectable objects (globals(), locals(), a class's __dict__) — scope is the abstract algorithm for searching across a sequence of these namespaces. Understanding both together clarifies why, for example, two different functions can each have a local variable named x without any conflict: they're simply different namespaces.
Example
x = "global namespace" def outer(): y = "outer's local namespace" print(locals()) # {'y': "outer's local namespace"} def inner(): z = "inner's local namespace" print(locals()) # {'z': "inner's local namespace"} inner() outer() print(globals()["x"]) # accessing the global namespace directly, like a dict
💡 Showing locals() / globals() as literal dictionaries you can inspect makes the otherwise abstract concept of "namespace" completely concrete — a strong way to demonstrate understanding beyond definitions.
What is a descriptor in Python?
Answer
A descriptor is any object that implements __get__, __set__, or __delete__, letting it customize attribute access when it's stored as a class attribute. Descriptors are the underlying mechanism that powers @property, methods, @staticmethod, and @classmethod.
Whenever you access instance.attribute, if attribute (found on the class, not the instance) is a descriptor, Python calls its __get__ method instead of just returning it directly — this hook is what allows @property to run custom logic while still looking like plain attribute access from the outside.
Example
class PositiveNumber: # a descriptor def __set_name__(self, owner, name): self.name = "_" + name def __get__(self, instance, owner): return getattr(instance, self.name) def __set__(self, instance, value): if value < 0: raise ValueError("Value must be positive") setattr(instance, self.name, value) class Product: price = PositiveNumber() # descriptor used as a class attribute p = Product() p.price = 100 # calls PositiveNumber.__set__ print(p.price) # calls PositiveNumber.__get__ -> 100 # p.price = -10 # raises ValueError -- validation happens automatically
💡 Explicitly stating " @property is essentially a built-in descriptor" directly connects this advanced topic back to 's OOP questions — showing the language's features as one consistent underlying mechanism rather than a list of unrelated syntax.
What is the difference between a data descriptor and a non-data descriptor?
Answer
A data descriptor implements both __get__ and __set__ (or __delete__); a non-data descriptor implements only __get__. This distinction matters because data descriptors take priority over an instance's own __dict__, while non-data descriptors do not — an instance attribute of the same name "wins" over a non-data descriptor.
This is exactly why instance methods (non-data descriptors, since functions only implement __get__) can be shadowed by assigning an instance attribute of the same name, while a @property (a data descriptor) cannot be shadowed the same way.
Example
class Example: def method(self): # a function -- non-data descriptor (only __get__) return "original method" e = Example() e.method = lambda: "shadowed!" # instance attribute successfully shadows the method print(e.method()) # 'shadowed!' -- non-data descriptor lost priority class WithProperty: @property # a property -- data descriptor (__get__ AND __set__) def value(self): return "from property" w = WithProperty() # w.value = "trying to shadow" # AttributeError (no setter) -- can't shadow this way at all
💡 This priority rule (data descriptors beat instance __dict__; non-data descriptors lose to it) is genuinely obscure but explains real, otherwise-confusing behavior — bringing it up unprompted is a strong seniorlevel signal.
How does @property relate to descriptors internally?
Answer
property is a built-in class that implements the full data descriptor protocol (__get__, __set__, __delete__) internally — when you write @property, you're creating an instance of this built-in descriptor class, wired up to the getter/setter/deleter functions you define.
Understanding this connection means you could, in principle, implement a simplified version of @property yourself using the descriptor protocol directly — which is exactly what interviewers sometimes ask as a advanced follow-up to test genuine understanding versus memorized usage.
Example
class SimpleProperty: # a hand-rolled, simplified @property def __init__(self, getter): self.getter = getter def __get__(self, instance, owner): if instance is None: return self return self.getter(instance) class Circle: def __init__(self, radius): self.radius = radius @SimpleProperty # using our own descriptor instead of @property def area(self): return 3.14159 * self.radius ** 2 c = Circle(5) print(c.area) # 78.53975 -- behaves just like a real @property, via our own descriptor
💡 Actually writing this simplified SimpleProperty class from memory (even without setter support) is one of the most convincing ways to demonstrate genuine descriptor mastery in an interview.
What is a metaclass in Python?
Answer
A metaclass is "the class of a class" — it controls how classes themselves are created, in the same way a regular class controls how its instances are created. By default, every class's metaclass is type; you can customize classcreation behavior by defining a custom metaclass.
This is genuinely advanced and relatively rarely needed in application code — frameworks (like Django's ORM, or ABCs internally) use metaclasses to automatically register subclasses, validate class definitions, or inject behavior into every class using them, but most everyday Python code never needs to define one.
Example
class MyClass: pass print(type(MyClass)) # <class 'type'> -- MyClass's metaclass is the built-in 'type' class Meta(type): # a custom metaclass def __new__(mcs, name, bases, namespace): print(f"Creating class: {name}") return super().__new__(mcs, name, bases, namespace) class MyModel(metaclass=Meta): # "Creating class: MyModel" prints at DEFINITION time pass
💡 The well-known Python community guideline applies here: "metaclasses are deeper magic than 99% of users should ever worry about — if you're wondering whether you need one, you don't." A strong answer demonstrates understanding while being honest that this is rarely the right tool for everyday problems.
How would you create a custom metaclass, and when would you actually need one?
Answer
Define a class that inherits from type, override __new__ or __init__ to customize class creation, and use it via class MyClass(metaclass=MyMeta):. Real use cases are narrow: automatic subclass registration, enforcing structural rules across all subclasses, or ORM-style declarative APIs.
Before reaching for a metaclass, it's worth checking whether a simpler tool — a class decorator, Q160), __init_subclass__ (a lighter-weight hook specifically for customizing subclass creation), or plain composition — solves the same problem with less complexity.
Example
class PluginMeta(type): registry = {} def __new__(mcs, name, bases, namespace): cls = super().__new__(mcs, name, bases, namespace) if name != "PluginBase": PluginMeta.registry[name] = cls # auto-register every subclass return cls class PluginBase(metaclass=PluginMeta): pass class CSVPlugin(PluginBase): # automatically registered, no extra code needed pass class JSONPlugin(PluginBase): pass print(PluginMeta.registry) # {'CSVPlugin': <class 'CSVPlugin'>, 'JSONPlugin': <class 'JSONPlugin'>}
💡 Mentioning __init_subclass__ as a simpler alternative that solves many "I need a metaclass" scenarios (like this exact plugin-registration example) without the added complexity is a strong, judgmentfocused answer.
What role does type() play in dynamically creating classes?
Answer
Calling type(name, bases, namespace) with three arguments dynamically creates a brand-new class at runtime — this is exactly what the class statement itself desugars to internally, meaning classes can be constructed programmatically without ever writing a class block.
This connects directly back to metaclasses (Q205): type is both the built-in function used for checking an object's type, and the default metaclass every ordinary class is an instance of — using it with three arguments is essentially calling that metaclass directly to manufacture a class.
Example
# Traditional class definition class Dog: def bark(self): return "Woof!" # Exactly equivalent, built dynamically with type() def bark_method(self): return "Woof!" DynamicDog = type("DynamicDog", (), {"bark": bark_method}) d = DynamicDog() print(d.bark()) # 'Woof!' -- behaves identically to the traditional class print(type(DynamicDog)) # <class 'type'>
💡 This is a great "prove you understand class creation, not just class usage" demonstration — being able to build an equivalent class both ways side-by-side is more convincing than describing type() 's threeargument form abstractly.
What is __slots__, and why would you use it?
Answer
__slots__ is a class-level declaration that restricts which instance attributes a class is allowed to have, and replaces the default per-instance __dict__ with a more compact fixed-size structure — reducing memory usage and slightly speeding up attribute access, at the cost of flexibility.
Without __slots__, every instance carries its own __dict__ for storing attributes, which is flexible (you can add any attribute at any time) but has real memory overhead — this matters when you're creating millions of small objects, where that per-instance dictionary overhead adds up significantly.
Example
class RegularPoint: def __init__(self, x, y): self.x, self.y = x, y class SlottedPoint: __slots__ = ("x", "y") # only these two attributes are allowed def __init__(self, x, y): self.x, self.y = x, y p1 = RegularPoint(1, 2) p1.z = 3 # works fine -- regular classes allow arbitrary new attributes p2 = SlottedPoint(1, 2) # p2.z = 3 # AttributeError -- 'z' isn't in __slots__ import sys print(sys.getsizeof(p1.__dict__)) # RegularPoint instances carry a full dict # SlottedPoint instances have no __dict__ at all -- more compact
💡 Frame __slots__ as a targeted optimization for a specific, measurable situation — "millions of small, fixed-shape objects" — rather than a default best practice for every class; using it indiscriminately trades away useful flexibility for a benefit that often doesn't matter.
What are the trade-offs of using __slots__?
Answer
You gain reduced memory footprint and marginally faster attribute access, but lose the ability to dynamically add new attributes, and multiple inheritance between classes with conflicting __slots__ becomes significantly more complicated (or outright disallowed in some configurations).
A subtler trade-off: a class using __slots__ cannot use default mutable class attributes the normal way for those slotted names, weak references require explicitly adding "__weakref__" to __slots__ if needed, and multiple inheritance from more than one class that each define non-empty __slots__ (with overlapping names) can raise a TypeError.
Example
class Base1: __slots__ = ("a",) class Base2: __slots__ = ("b",) class Combined(Base1, Base2): # fine -- non-overlapping slots __slots__ = ("c",) c = Combined() c.a, c.b, c.c = 1, 2, 3 print(c.a, c.b, c.c) # 1 2 3 # But if Base1 and Base2 both declared __slots__ = ("a",) -- SAME name -- # this combination would raise: TypeError: multiple bases have instance lay-out conflict
💡 A strong answer treats __slots__ as a genuine trade-off decision, not a free performance win — "I'd only reach for this after profiling shows memory is actually a bottleneck for a specific high-volume class, not by default."
What is monkey patching, and when (if ever) is it appropriate?
Answer
Monkey patching is modifying or extending existing code — a class, module, or object — at runtime, from outside its original definition, without touching the original source. It's powerful but risky, generally reserved for tests (mocking), temporary hotfixes, or working around a bug in third-party code you can't otherwise modify.
The core danger is that monkey patches are invisible at the point of definition — someone reading the original class has no way of knowing its behavior has been altered elsewhere, which can make bugs extremely difficult to trace, especially as a codebase grows.
Example
class PaymentService: def charge(self, amount): return f"Charged ${amount} via real payment gateway" # Monkey patching for a test -- a legitimate, very common use case def fake_charge(self, amount): return f"Charged ${amount} (test mode, no real transaction)" PaymentService.charge = fake_charge # patched at runtime, no source code changed service = PaymentService() print(service.charge(100)) # 'Charged $100 (test mode, no real transaction)'
What is typing.Protocol, and how does it relate to duck typing?
Answer
Protocol (from the typing module, Python 3.8+) lets you define a structural interface — a set of methods/ attributes an object must have — that a static type checker (like mypy) can verify without the object needing to explicitly inherit from anything. It's essentially "duck typing with static type-checking support."
This solves a real gap: before Protocol, expressing "any object with a.quack() method" as a type hint required either an ABC (forcing explicit inheritance) or giving up on static type checking for that parameter entirely. Protocol gives you the flexibility of duck typing, Q99) with the safety net of static analysis.
Example
from typing import Protocol class Quacker(Protocol): def quack(self) -> str: ... class Duck: # NOT explicitly related to Quacker via inheritance def quack(self) -> str: return "Quack!" class Person: def quack(self) -> str: return "I am imitating a duck!" def make_it_quack(thing: Quacker) -> str: # accepts ANYTHING with a compatible quack() return thing.quack() print(make_it_quack(Duck())) # fine -- structurally matches Quacker print(make_it_quack(Person())) # also fine -- mypy would accept this too, no inheritance needed
💡 Framing Protocol as "duck typing that a static type checker can actually verify" is the cleanest way to connect this modern feature to the classic, already-understood concept of duck typing from.
What are generic type hints, and how have they evolved in recent Python versions?
Answer
Generic type hints describe the contents of a container, not just its outer type — e.g., "a list of integers" rather than just "a list." Since Python 3.9, you can use built-in types directly for this (list[int]), instead of the older, more verbose typing.List[int] required in earlier versions.
Before 3.9, generic hints required importing capitalized equivalents from the typing module (List, Dict, Tuple, Set) since the built-in list, dict, etc. didn't support the subscript syntax (list[int]) at all — PEP 585 changed this, letting built-ins be used generically directly, which is now the preferred modern style.
Example
# Modern style (Python 3.9+) -- preferred def process(items: list[int]) -> dict[str, int]: return {"count": len(items)} # Older style (still works, needed for Python < 3.9) from typing import List, Dict def process_old(items: List[int]) -> Dict[str, int]: return {"count": len(items)}
💡 If asked to write type hints live, default to the modern list[int] / dict[str, int] style unless the role specifically mentions supporting older Python versions — it signals current, idiomatic knowledge.
What do Optional and Union mean in type hints?
Answer
Union[X, Y] means a value can be either type X or type Y. Optional[X] is shorthand for Union[X, None] — "this can be an X, or it can be missing/ None." Since Python 3.10, the | operator provides a more concise alternative syntax for both: X | Y and X | None.
Optional doesn't mean "this parameter has a default value" (a common misconception) — it specifically means the value's type includes None as a possibility, independent of whether the parameter also happens to have a default.
Example
from typing import Optional, Union def find_user(user_id: int) -> Optional[dict]: # returns a dict, OR None if not found return database.get(user_id) # might legitimately be None def parse_value(raw: Union[str, int]) -> int: # accepts either a str or an int return int(raw) # Modern 3.10+ syntax, generally preferred now: def find_user_modern(user_id: int) -> dict | None: return database.get(user_id) def parse_value_modern(raw: str | int) -> int: return int(raw)
What are dataclasses, and what problem do they solve?
Answer
@dataclass (from the dataclasses module, 3.7+) is a class decorator that automatically generates common boilerplate methods — __init__, __repr__, and __eq__ — for classes that primarily exist to hold data, based purely on type-annotated class attributes.
Before dataclasses, writing a simple data-holding class meant manually writing a repetitive __init__ (assigning each parameter to self), a __repr__ for readable debugging output, and an __eq__ for value comparison — all mechanical, easy-to-get-slightly-wrong boilerplate that @dataclass eliminates entirely.
Example
# Without dataclasses -- lots of repetitive boilerplate class PointManual: def __init__(self, x, y): self.x = x self.y = y def __repr__(self): return f"PointManual(x={self.x}, y={self.y})" def __eq__(self, other): return (self.x, self.y) == (other.x, other.y) # With dataclasses -- all of the above generated automatically from dataclasses import dataclass @dataclass class Point: x: int y: int p1 = Point(1, 2) print(p1) # Point(x=1, y=2) -- __repr__ generated automatically print(p1 == Point(1, 2)) # True -- __eq__ generated automatically
💡 Framing @dataclass as "eliminating boilerplate for __init__ / __repr__ / __eq__ " directly, with a before/after comparison, is far more convincing than describing it abstractly as "a decorator for data classes."
What features does @dataclass provide, and how do you customize them?
Answer
By default, @dataclass generates __init__, __repr__, and __eq__. Optional keyword arguments to the decorator enable more: order=True adds comparison operators (<, <=, etc.), and frozen=True makes instances immutable (Q216).
Fields can also use dataclasses.field() for more control — specifying a default_factory for mutable defaults (directly solving the mutable default argument trap from, Q61, in a dataclass-specific way), or excluding a field from the generated __repr__ or __eq__.
Example
from dataclasses import dataclass, field @dataclass(order=True) # adds <, <=, >, >= based on field order class Product: name: str price: float tags: list = field(default_factory=list) # safe mutable default! p1 = Product("Widget", 9.99) p2 = Product("Gadget", 19.99) print(p1 < p2) # True -- compares by field order (name, then price) p1.tags.append("sale") p3 = Product("Widget", 9.99) print(p3.tags) # [] -- independent list, thanks to default_factory
💡 Mentioning field(default_factory=list) as the dataclass-specific solution to the mutable default argument problem ties this section directly back to one of the most-cited traps in the entire guide, Q61).
How do you make a dataclass immutable?
Answer
Pass frozen=True to the @dataclass decorator — this makes attempting to assign to any field after construction raise a FrozenInstanceError, and also automatically makes instances hashable (since immutability is a prerequisite for safe hashing, per, Q43).
A frozen dataclass is a clean, concise way to create immutable "value objects" — similar in spirit to a namedtuple, but with the readability and flexibility of full dataclass syntax, type hints, and default values.
Example
from dataclasses import dataclass @dataclass(frozen=True) class Coordinates: latitude: float longitude: float c = Coordinates(40.7128, -74.0060) # c.latitude = 0.0 # dataclasses.FrozenInstanceError: cannot assign to field 'latitude' # Frozen dataclasses are hashable by default, so they can be used in sets/dict keys: locations_seen = {c, Coordinates(40.7128, -74.0060)} print(len(locations_seen)) # 1 -- treated as equal and deduplicated
💡 Connect frozen=True back to the hashability rules from (Q43) — mutable objects generally can't be safely hashed, so it makes sense that Python only makes a frozen dataclass hashable by default.
What is the difference between a dataclass, a regular class, and a namedtuple?
Answer
A regular class requires you to write all boilerplate manually. A namedtuple is lightweight, immutable, and tuple-based (supports indexing/unpacking) but lacks type hints and default value flexibility. A @dataclass sits in between — full class flexibility (methods, inheritance, mutability by choice) with auto-generated boilerplate and proper type annotations.
Key points
- 1Boilerplate — Regular Class: You write it all; namedtuple: Auto-generated; @dataclass: Auto-generated
- 2Mutability — Regular Class: Mutable by default; namedtuple: Immutable; @dataclass: Mutable by default (or frozen)
- 3Type hints — Regular Class: Optional, not enforced by the tool itself; namedtuple: No native type hint support; @dataclass: Full type hint support
- 4Tuple-like (unpacking, indexing) — Regular Class: No; namedtuple: Yes; @dataclass: No (unless added manually)
- 5Inheritance/methods — Regular Class: Full support; namedtuple: Limited; @dataclass: Full support
Example
from collections import namedtuple from dataclasses import dataclass PointNT = namedtuple("PointNT", ["x", "y"]) p1 = PointNT(1, 2) x, y = p1 # tuple-style unpacking works print(p1[0]) # 1 -- tuple-style indexing works too @dataclass class PointDC: x: int y: int p2 = PointDC(1, 2) # x, y = p2 # TypeError -- dataclasses aren't unpackable like tuples by default
💡 "Use namedtuple for simple, truly immutable, tuple-like records; use @dataclass when you want type hints, mutability options, or plan to add real methods" is a clean, practical decision rule to offer.
What are some of the most useful functions in the functools module?
Answer
Beyond wraps, lru_cache, partial, and reduce (covered in, other commonly used tools include functools.total_ordering (derives all comparison operators from just __eq__ and one other), functools.cmp_to_key (adapts an old-style comparison function for use with sorted()), and functools.singledispatch (Q219).
total_ordering is especially handy when you need full ordering support (<, <=, >, >=) on a custom class but don't want to hand-write all four methods — you implement just __eq__ and one of them, and the decorator fills in the rest.
Example
from functools import total_ordering @total_ordering class Version: def __init__(self, major, minor): self.major, self.minor = major, minor def __eq__(self, other): return (self.major, self.minor) == (other.major, other.minor) def __lt__(self, other): return (self.major, self.minor) < (other.major, other.minor) # total_ordering derives __le__, __gt__, __ge__ automatically from the two above v1, v2 = Version(1, 0), Version(2, 0) print(v1 < v2, v1 <= v2, v1 > v2, v1 >= v2) # True True False False
💡 total_ordering is a great small example to show alongside operator overloading, Q111) — it demonstrates knowing the lazy, DRY way to add full comparison support instead of writing all four methods by hand.
What is functools.singledispatch, and how does it work?
Answer
singledispatch lets you define a generic function with multiple type-specific implementations, chosen automatically at call time based on the type of the first argument — providing genuine, elegant function overloading based on type, something Python doesn't support natively, Q98).
This is meaningfully cleaner than manually branching on isinstance() checks inside one big function — each type's implementation is registered separately, keeping the logic for each type isolated and independently extensible (even by other modules, after the fact).
Example
from functools import singledispatch @singledispatch def describe(value): # the default/fallback implementation return f"Some value: {value}" @describe.register def _(value: int): return f"An integer: {value}" @describe.register def _(value: list): return f"A list with {len(value)} items" print(describe(42)) # 'An integer: 42' print(describe([1, 2, 3])) # 'A list with 3 items' print(describe(3.14)) # 'Some value: 3.14' -- falls back to the default
💡 This is the direct, elegant answer to "how would you simulate method overloading in Python" for the specific case of dispatching by argument type — a much cleaner solution than the manual isinstance() chains most candidates default to.
What are the most useful tools in the itertools module?
Answer
Commonly used tools include chain (concatenate multiple iterables), count / cycle / repeat (infinite iterators), combinations / permutations (combinatorics), groupby (group consecutive matching items), and islice (slice a lazy iterator without materializing it).
itertools functions are all lazy (return iterators, not lists), which means they compose naturally with the generator-based pipelines from — you get combinatorial and iteration utilities without sacrificing the memory efficiency generators are chosen for in the first place.
Example
from itertools import chain, combinations, islice, groupby print(list(chain([1, 2], [3, 4]))) # [1, 2, 3, 4] -- concatenates iterables lazily print(list(combinations([1, 2, 3], 2))) # [(1, 2), (1, 3), (2, 3)] print(list(islice(range(1000000), 5))) # [0, 1, 2, 3, 4] -- lazy slice, no huge list built data = [1, 1, 2, 2, 2, 3, 1] for key, group in groupby(data): print(key, list(group)) # 1 [1, 1] # 2 [2, 2, 2] # 3 [3] # 1 [1] -- note: groupby only groups CONSECUTIVE matches, not all occurrences
What does itertools.chain do, and when would you use it?
Answer
chain(*iterables) lazily concatenates multiple iterables into a single iterator, letting you loop over them as if they were one sequence, without first combining them into a new, fully materialized list.
This is more memory-efficient than list1 + list2 (which creates a whole new list in memory) when you only need to iterate over the combined sequence once — and it works with any iterables, not just lists, including generators.
Example
from itertools import chain list1 = [1, 2, 3] list2 = [4, 5, 6] # Less efficient: builds an entirely new combined list in memory combined_eager = list1 + list2 # More efficient: lazy, no new list built, works with any iterables for item in chain(list1, list2): print(item) # 1 2 3 4 5 6 # Also works seamlessly with generators, unlike '+' gen1 = (x for x in range(3)) gen2 = (x for x in range(3, 6)) print(list(chain(gen1, gen2))) # [0, 1, 2, 3, 4, 5]
💡 Point out that chain works with any mix of iterables (lists, generators, ranges) at once — + only works between two objects of the exact same type, which is a real practical limitation chain avoids entirely.
What are collections.Counter, defaultdict, and OrderedDict used for?
Answer
Counter counts hashable items automatically (perfect for frequency analysis). defaultdict provides an automatic default value for missing keys, eliminating manual existence checks. OrderedDict is a dict that remembers insertion order — now largely redundant since regular dicts guarantee order since Python 3.7, but still useful for its extra order-specific methods.
defaultdict is especially useful for grouping data, Q42 mentioned.setdefault() for the same purpose) — defaultdict(list) lets you simply call.append() on any key without first checking whether that key already exists.
Example
from collections import Counter, defaultdict, OrderedDict # Counter: word frequency counting, a very common interview micro-task words = ["apple", "banana", "apple", "cherry", "apple"] counts = Counter(words) print(counts) # Counter({'apple': 3, 'banana': 1, 'cherry': 1}) print(counts.most_common(1)) # [('apple', 3)] # defaultdict: no manual "if key not in dict" checks needed groups = defaultdict(list) for word in words: groups[word[0]].append(word) # works even the first time a letter is seen print(dict(groups)) # {'a': ['apple', 'apple', 'apple'], 'b': ['banana'], 'c': ['cherry']} # OrderedDict: mostly historical now, but has move_to_end() and an order-aware __eq__ od = OrderedDict([("a", 1), ("b", 2)]) od.move_to_end("a") print(od) # OrderedDict([('b', 2), ('a', 1)])
💡 Counter is an extremely common building block for "count word frequency" or "find the most common element" interview questions — knowing.most_common(n) specifically saves you from manually sorting a dictionary by value.
What is collections.namedtuple?
Answer
namedtuple creates a lightweight, immutable, tuple-based class with named fields — you get the memory efficiency and immutability of a tuple, plus readable attribute-style access (point.x instead of point[0]).
This bridges the readability gap of plain tuples (where point[0] gives no hint what it represents) without the overhead of a full custom class — though @dataclass (Q217) has largely superseded namedtuple for cases needing more flexibility, like mutability or custom methods.
Example
from collections import namedtuple Point = namedtuple("Point", ["x", "y"]) p = Point(1, 2) print(p.x, p.y) # 1 2 -- readable attribute access print(p[0], p[1]) # 1 2 -- still works like a regular tuple too x, y = p # unpacking works, just like a plain tuple # p.x = 10 # AttributeError -- namedtuples are immutable, like regular tuples
💡 If asked "namedtuple or dataclass," the practical rule is: namedtuple for simple, truly immutable records where tuple-like behavior (unpacking, indexing) matters; @dataclass for anything needing type hints, optional mutability, or real methods.
What is collections.deque, and why is it more efficient than a list for queue operations?
Answer
deque ("double-ended queue") supports O(1) appends and pops from both ends, whereas a regular list is O(1) only at the end and O(n) at the front (since every remaining element must shift when you insert or remove from the beginning).
This makes deque the correct choice for implementing queues, sliding-window algorithms, or any pattern needing efficient operations at both ends — using a plain list for a queue (repeatedly calling.pop(0)) is a common performance anti-pattern in real code and technical interviews alike.
Example
from collections import deque import time d = deque([1, 2, 3]) d.appendleft(0) # O(1) -- fast d.append(4) # O(1) -- fast print(d) # deque([0, 1, 2, 3, 4]) print(d.popleft()) # O(1) -- fast removal from the front print(d.pop()) # O(1) -- fast removal from the back # A plain list's pop(0) is O(n) -- every remaining element must shift down lst = [1, 2, 3, 4, 5] lst.pop(0) # works, but is O(n) -- avoid this in a hot loop on large lists
What are weak references, and when would you use them?
Answer
A weak reference (via the weakref module) refers to an object without increasing its reference count — meaning the object can still be garbage collected even while a weak reference to it exists. This is used to avoid creating reference cycles or unwanted memory retention, especially in caches and observer-pattern implementations.
A classic use case is a cache that shouldn't be the reason an object stays alive — using weak references lets cached objects be garbage collected normally once nothing else needs them, automatically evicting them from the cache rather than leaking memory indefinitely.
Example
import weakref class Resource: def __init__(self, name): self.name = name r = Resource("database_connection") weak_r = weakref.ref(r) # doesn't increase r's reference count print(weak_r()) # <Resource object> -- call it like a function to access the object del r # normal (strong) reference removed print(weak_r()) # None -- object was garbage collected; the weak ref doesn't keep it alive # weakref.WeakValueDictionary automatically drops entries once their values are collected cache = weakref.WeakValueDictionary()
💡 Connecting weak references directly to breaking reference cycles (Q198) — e.g., a child object holding a weak reference back to its parent instead of a strong one — demonstrates that you see how these advanced memory-management concepts fit together practically.
How would you profile a Python program to find performance bottlenecks?
Answer
Use the standard library's cProfile module to get a function-by-function breakdown of where time is actually being spent, rather than guessing — profiling first, optimizing second, is the fundamental discipline here.
cProfile shows call counts and cumulative time per function, which is usually enough to identify the "hot path" worth optimizing; for line-by-line detail within a specific already-identified function, tools like line_profiler go a level deeper.
Example
import cProfile def slow_function(): total = 0 for i in range(1_000_000): total += i ** 2 return total cProfile.run("slow_function()") # Prints a breakdown: number of calls, total time, time per call, cumulative time, per function # For command-line profiling of an entire script: # python -m cProfile -s cumulative my_script.py
💡 "Measure first, optimize second" is the key principle to state explicitly — guessing at bottlenecks and optimizing the wrong part of the code is a very common and wasteful mistake that profiling directly prevents.
What are common Python performance optimization techniques?
Answer
After profiling identifies the actual bottleneck: use built-in functions and the standard library (implemented in optimized C) instead of manual Python loops where possible, choose the right data structure for the access pattern, cache expensive repeated computations (lru_cache), and consider NumPy /vectorization for heavy numerical work.
A recurring theme across many of this guide's sections is directly relevant here: comprehensions over manual loops, deque over list for queue operations, set over list for membership testing, generators for memory efficiency — performance and idiomatic Python often point in the same direction.
Example
# Slower: manual loop, repeated attribute lookups result = [] for i in range(1000000): result.append(i * 2) # Faster: comprehension, fewer bytecode operations result = [i * 2 for i in range(1000000)] # Faster still for large numeric workloads: vectorized with NumPy import numpy as np arr = np.arange(1000000) result = arr * 2 # operates in optimized C, not a Python-level loop at all from functools import lru_cache @lru_cache(maxsize=None) def expensive_computation(n): return sum(i ** 2 for i in range(n))
💡 Always frame optimization as something that follows measurement — "I'd profile first to confirm where time is actually going, then apply the specific technique that addresses that bottleneck" — rather than reciting a generic list of tricks as if they apply everywhere equally.
What is the difference between CPython, PyPy, and other Python implementations in terms of performance?
Answer
CPython (the standard, most widely used implementation) compiles to bytecode and interprets it without JIT compilation by default. PyPy uses a JIT (just-in-time) compiler that can dramatically speed up long-running, CPUbound pure-Python code — sometimes by an order of magnitude — at the cost of slightly different compatibility with C-extension-heavy libraries.
PyPy's speedup is most dramatic for long-running programs with lots of repeated, hot execution paths (loops, function calls) that the JIT can detect and compile to efficient machine code over time — short-lived scripts don't benefit as much, since there's less time for the JIT to "warm up" and pay off its own overhead.
Example
# The same pure-Python code runs on both implementations, but performs very differently: def fibonacci(n): if n < 2: return n return fibonacci(n - 1) + fibonacci(n - 2) print(fibonacci(30)) # Under CPython: interpreted bytecode, no JIT # Under PyPy: JIT-compiled after the "hot" recursive calls are detected, often much faster
💡 Mention the trade-off honestly: PyPy's speed gains are real for CPU-bound pure-Python code, but its compatibility with certain C-extension-heavy libraries (some NumPy/pandas-heavy data science stacks) has historically been more limited than CPython's — it's not a universal drop-in upgrade.
What is object interning, and which types does CPython intern automatically?
Answer
Interning is reusing a single shared object for multiple equal values, instead of creating a new object every time, to save memory. CPython automatically interns small integers (-5 to 256) and many string literals that look like identifiers, though this is an implementation detail, not a language guarantee.
This connects directly back to two earlier "traps" in this guide — 's is vs == question and 's string immutability discussion — interning is why a is b can appear to work correctly for small integers or simple strings, even though relying on that behavior for general value comparison is fundamentally incorrect and implementation-dependent.
Example
a = 100 b = 100 print(a is b) # True -- small integers (-5 to 256) are interned by CPython c = 1000 d = 1000 print(c is d) # False (usually) -- outside the small-integer cache range s1 = "hello" s2 = "hello" print(s1 is s2) # True -- simple, identifier-like string literals are often interned s3 = "hello world!" s4 = "hello world!" print(s3 is s4) # Often False -- strings with spaces/punctuation are less likely interned import sys s5 = sys.intern("some long string") # force interning manually if truly needed
💡 This question ties the whole guide together nicely — reference this as "the underlying implementation detail behind the is -vs- == trap from, and the string immutability discussion from " to show you retain and connect concepts across a long interview rather than treating each question in isolation.
What are best practices for writing memory-efficient Python code?
Answer
Prefer generators over lists for large or one-pass data, use __slots__ for classes instantiated in very large numbers (Q208), choose appropriate data structures (deque, set) for their access patterns, avoid unnecessary object copies (understand shallow vs. deep copy, and profile memory usage before optimizing rather than guessing.
As with performance generally (Q227), memory optimization should follow measurement — tools like tracemalloc (standard library) or memory_profiler (third-party) can pinpoint exactly which part of a program is actually consuming the most memory, rather than optimizing based on assumptions.
Example
import tracemalloc tracemalloc.start() # ... run the code you want to measure ... data = [i for i in range(1_000_000)] # a deliberately memory-heavy operation current, peak = tracemalloc.get_traced_memory() print(f"Current memory usage: {current / 1024 / 1024:.2f} MB") print(f"Peak memory usage: {peak / 1024 / 1024:.2f} MB") tracemalloc.stop() # A generator would use dramatically less memory for the same logical sequence: data_efficient = (i for i in range(1_000_000))
💡 As a closing answer for this section, tie together the specific techniques from across the whole guide by name (generators, __slots__, deque, avoiding unnecessary deep copies) rather than offering only generic advice — it demonstrates the full breadth of what you've covered, applied to one practical goal.
Recommended resourcesAffiliate links · may earn us a commission