Advanced Python Interview Questions
Last updated 2026-11-19
Advanced Python interviews dig into how the language works rather than how to use its syntax: descriptors, the data model, attribute lookup, asyncio internals, typing and performance. They suit candidates with several years of experience and often include live debugging or code review.
Each answer here explains the mechanism and then the practical consequence, since that is the pattern interviewers reward. Several questions are output predictions on subtle behaviours of the language.
| Level | 3 to 7 years |
|---|---|
| Focus | Data model, descriptors, asyncio, typing, performance |
| Version | Python 3.10 and later |
What separates strong answers
Describe the protocol, not just the feature: for example, a property is a descriptor, and attribute access calls __getattribute__ first. Naming the mechanism shows you could debug a case you have never seen.
- Know which behaviour is a language guarantee and which is CPython-specific
- Back claims with a two-line demonstration
- Mention cost: memory, speed or readability
Prerequisites
Make sure the basics are firm first: the main Python page, Python OOPs and decorators. Concurrency specifics are on the multithreading and multiprocessing page, and overall planning in how to crack a Python interview.
Advanced Python Interview Questions: questions with worked answers
1 What is a descriptor, and how do properties and methods use it?
hardA descriptor is an object that defines __get__, and optionally __set__ or __delete__, stored as a class attribute. When an attribute is looked up on an instance, Python calls the descriptor's methods. Functions are non-data descriptors whose __get__ binds self, which is how methods work. A property is a data descriptor implemented in the same way. A data descriptor, which defines __set__, takes priority over the instance dictionary; a non-data one does not.
pythonclass Positive: def __set_name__(self, owner, name): self.n = "_" + name def __get__(self, obj, typ=None): return getattr(obj, self.n) def __set__(self, obj, v): if v <= 0: raise ValueError("must be positive") setattr(obj, self.n, v) class Box: w = Positive() def __init__(self, w): self.w = w print(Box(3).w) # 3 Box(-1) # ValueError2 Explain attribute lookup order.
hardobj.x calls type(obj).__getattribute__. The default checks, in order: a data descriptor found on the type's MRO, then the instance __dict__, then a non-data descriptor or plain class attribute from the MRO, and finally falls back to __getattr__ if defined. __getattr__ runs only when normal lookup fails, which makes it suitable for delegation and lazy attributes, while overriding __getattribute__ affects every access and risks infinite recursion.
3 Predict the output: why does a mutable class attribute surprise subclasses?
hardA class attribute is shared by the class and subclasses until one assigns its own. Mutating through any name changes the shared object, but assignment on a subclass creates a new attribute on that subclass only.
pythonclass A: data = [] class B(A): pass B.data.append(1) print(A.data) # [1] B.data = [9] print(A.data, B.data) # [1] [9]4 What are __enter__ and __exit__, and what does returning True from __exit__ do?
mediumThey implement the context manager protocol used by with. __enter__ runs at the start and its return value is bound by as. __exit__ receives the exception type, value and traceback, or three Nones if there was no error, and runs on exit. Returning a true value suppresses the exception, so it should be done deliberately, as in contextlib.suppress.
pythonclass Quiet: def __enter__(self): return self def __exit__(self, t, v, tb): return t is ZeroDivisionError with Quiet(): 1 / 0 print("continued") # continued5 How does asyncio work? What is the event loop?
hardasyncio runs coroutines on a single-threaded event loop. A coroutine runs until it awaits something that is not ready, then yields control, and the loop resumes another ready task. Waiting on I/O uses the operating system's selector, so thousands of connections cost little. Tasks are created with asyncio.create_task and run concurrently, while awaiting coroutines one after another runs them sequentially. A blocking call such as time.sleep or a CPU loop stalls everything, so use asyncio.to_thread or an executor for blocking work.
pythonimport asyncio, time async def job(n): await asyncio.sleep(1) return n async def main(): t = time.perf_counter() a = await job(1); b = await job(2) # sequential, about 2s c, d = await asyncio.gather(job(3), job(4)) # concurrent, about 1s print(a, b, c, d, round(time.perf_counter() - t)) # 1 2 3 4 3 asyncio.run(main())6 What are type hints, and does Python enforce them?
mediumType hints are annotations such as def f(x: int) -> str that document intent and let static checkers like mypy or pyright catch errors before runtime. The interpreter itself does not enforce them: calling f('a') still runs. They are stored in __annotations__ and used by libraries such as dataclasses and pydantic at runtime. Useful tools include Optional or the X | None form, Protocol for structural typing, TypedDict, Generic and Literal.
7 What is the difference between __new__ and __init__, and when do you override __new__?
hard__new__ is a static method that creates and returns the instance, while __init__ initialises it afterwards. Override __new__ to control creation: singletons, caching instances, or subclassing immutable types like int, str and tuple, where the value must be fixed before __init__ would run.
pythonclass Singleton: _inst = None def __new__(cls): if cls._inst is None: cls._inst = super().__new__(cls) return cls._inst print(Singleton() is Singleton()) # True8 Why is dict lookup O(1) on average, and what are hash collisions' effect?
hardPython hashes the key to a slot and uses open addressing with perturbation to probe on collisions. With a good hash and a load factor kept under about two thirds by resizing, expected probes are constant. Many keys with equal hashes force long probe sequences and degrade towards O(n), which is why hash randomisation for strings exists, to resist deliberately crafted collisions.
9 What are walrus operator and structural pattern matching, and where do they help?
mediumThe walrus operator := assigns inside an expression, useful for avoiding a repeated call in while or if conditions and comprehensions. match and case, from Python 3.10, do structural pattern matching: they destructure sequences, mappings and class instances and bind names, not just compare values. A bare name in a pattern is a capture, not a comparison, a frequent trap.
pythondef kind(x): match x: case [a, b]: return f"pair {a},{b}" case {"id": i}: return f"record {i}" case int() | float(): return "number" case _: return "other" print(kind([1, 2]), kind({"id": 7}), kind(3.5)) # pair 1,2 record 7 number10 How do you profile and speed up slow Python code?
hardMeasure first. cProfile shows where time goes by function, line profilers refine to lines, and timeit benchmarks small snippets. Typical wins: a better algorithm or data structure, hoisting work out of loops, using built-ins and comprehensions implemented in C, caching with lru_cache, vectorising with NumPy, and moving CPU-bound work to processes or native extensions. Micro-optimisations come last.
pythonimport timeit print(timeit.timeit("x in s", "s = set(range(1000)); x = 999", number=100000) < timeit.timeit("x in s", "s = list(range(1000)); x = 999", number=100000)) # True11 What is the difference between __getattr__ and __getattribute__?
hard__getattribute__ is called for every attribute access on an instance. __getattr__ is the fallback, called only when the normal lookup raises AttributeError. Overriding __getattribute__ requires using object.__getattribute__(self, name) inside to avoid infinite recursion. Most delegation and proxy code needs only __getattr__.
pythonclass Proxy: def __init__(self, t): self._t = t def __getattr__(self, name): return getattr(self._t, name) p = Proxy([3, 1, 2]) p.sort() print(p._t) # [1, 2, 3]12 How do you implement a thread-safe singleton or a cache with expiry?
hardFor a singleton, a module-level instance is the simplest and thread-safe because modules import once. If lazy creation is needed, guard creation with a lock and double-check inside it. For a time-limited cache, store the value with a timestamp, compare against time.monotonic() on read, and protect writes with a lock. For production use, prefer a vetted library over a hand-rolled version.
13 What are the common ways to make a class hashable and orderable?
mediumDefine __eq__ and a consistent __hash__ based on the same immutable fields. For ordering, define __lt__ and apply functools.total_ordering, or use a dataclass with order=True, or compare tuples of fields. A dataclass with frozen=True and eq=True generates a hash automatically.
pythonfrom dataclasses import dataclass @dataclass(frozen=True, order=True) class Ver: major: int minor: int print(Ver(1, 2) < Ver(1, 10), len({Ver(1, 2), Ver(1, 2)})) # True 1
Frequently asked questions
Which advanced Python topics are asked most?
Decorators and closures, generators, context managers, the GIL and concurrency choices, asyncio, descriptors and the data model, typing and performance profiling.
Do I need to know metaclasses?
Know what they are and when they are overkill. Most uses are replaceable by class decorators or __init_subclass__.
Is asyncio faster than threads?
For many concurrent network connections, yes, because of lower per-task overhead. For CPU-bound work neither helps, and for a handful of blocking calls threads are simpler.
How do I stand out in a senior Python interview?
Explain trade-offs and failure modes, not just features, and back each claim with a short demonstration.
Related guides
More in Programming Language Interview Questions by Language
- ASP.NET Core MVC Interview Questions
- C Language Interview Questions and Answers
- C Pointers Interview Questions
- C Programming Output Questions with Answers
- C# Async Await Interview Questions
- C# Coding Interview Questions
- C# Collections Interview Questions
- C# Delegates and Events Interview Questions
- C# Interview Questions and Answers
- C# LINQ Interview Questions
- C# OOPs Interview Questions
- C++ Coding Interview Questions