Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 77 ยท Python Interview Questions

Python: OOP, MRO and the GIL

Prepare Python interview answers on inheritance, MRO and super(), dataclasses, the GIL, and when to choose threads, processes or asyncio, with runnable code.

Object-oriented questions in Python interviews go one level deeper than "what is inheritance?". Expect multiple inheritance, super(), how Python decides which method wins, dataclasses, and the famous Global Interpreter Lock. The second half of the lesson is the GIL question: "threads, processes or asyncio?"

For the full tutorials see Inheritance, Dataclasses, Concurrency and asyncio.

Pick the right tool

Threads Waiting on I/O. Shared memory.
Processes Heavy CPU work. Separate memory.
asyncio Thousands of waiting connections.

The GIL only hurts CPU-bound code in threads.

1 / 2

Inheritance and the MRO

Q: How does Python resolve a method with multiple inheritance? It follows the method resolution order (MRO): a linear list of classes computed by the C3 algorithm. The rules are that a class comes before its parents, and the order of base classes in the class line is respected. You can see it with Class.__mro__ or Class.mro().

Q: What is the diamond problem? Two parents share a grandparent, so a naive search could visit the grandparent twice or in the wrong order. C3 puts the shared base last, and visits it once.

Python The diamond and its MRO

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The output shows that super() in B calls C, not A. That surprises people.

Q: What does super() actually do? It does not mean "my parent". It means "the next class after the current one in the MRO of type(self)". That is why cooperative multiple inheritance works when every class calls super().

Python Cooperative __init__ with super()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Class attributes, methods and properties

Q: What is the difference between @staticmethod, @classmethod and an instance method? An instance method receives self. A class method receives the class as cls (use it for alternative constructors and it works with subclasses). A static method receives nothing special: it is a plain function stored in the class namespace.

Q: What happens with a mutable class attribute? It is shared by all instances. Assigning self.items = [] in __init__ makes it per-instance; mutating Class.items affects everyone.

Python Class methods, shared attributes and properties

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Dataclasses

Q: What does @dataclass give you? It writes __init__, __repr__ and __eq__ from annotated fields. Options add ordering (order=True), immutability (frozen=True, which also makes instances hashable with eq=True), and slots=True. The classic trap: a mutable default such as [] is rejected, and you must use field(default_factory=list).

Python Dataclass features and the mutable default trap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The GIL

Q: What is the GIL? The Global Interpreter Lock in CPython (the standard implementation) lets only one thread execute Python bytecode at a time within a process. It exists to keep memory management (reference counting) simple and fast for single-threaded code. Consequences:

  • Threads do not speed up CPU-bound pure Python code.
  • Threads do help with I/O: a thread waiting on a socket or sleep releases the lock.
  • Many C extensions (NumPy, hashing, compression) release the GIL during heavy work.
  • The GIL does not make your code thread-safe: counter += 1 is several bytecodes and can interleave, so shared data still needs a threading.Lock.

Be careful with version claims. Recent CPython releases offer an optional free-threaded build without the GIL, but it is not the default build, so "Python has a GIL" is still the right default answer.

This is how you would show that threads overlap waiting. It is read-only because the in-browser Python runtime cannot start threads:

Python
import time
from concurrent.futures import ThreadPoolExecutor

def wait(_):
    time.sleep(0.2)          # sleeping releases the GIL

with ThreadPoolExecutor(max_workers=5) as pool:
    list(pool.map(wait, range(5)))   # about 0.2 s in total, not 1 s

A stand-in for the race

Real threads cannot run on this page, so here is a deterministic stand-in. It models counter += 1 as three steps (read, add, write) and lets two "threads" take turns step by step. This is the interleaving that a real thread switch can produce:

Python Why counter += 1 is not atomic

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The fix on a real interpreter is to hold a threading.Lock around the whole read-modify-write:

Python
with lock:
    counter += 1

Threads, processes or asyncio?

Situation Choice Why
Many slow network or disk calls threading or asyncio Waiting releases the GIL
Thousands of concurrent connections asyncio One thread, tiny cost per task
CPU-heavy pure Python multiprocessing / ProcessPoolExecutor Each process has its own GIL
Heavy numeric work NumPy or similar The C code runs outside the GIL

asyncio is cooperative: tasks switch only at await, so one blocking call freezes everything. Processes cost more memory and data must be pickled between them.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In class D(B, C), what does super().method() inside B call when B and C share the base A?

    super() follows the MRO of the instance's class, not of the class where the code is written.
  2. 2. Which task benefits least from adding threads in CPython?

    CPU-bound Python code is serialized by the GIL. The other tasks mostly wait, which releases the lock.
  3. 3. Why does items: list = [] fail inside a dataclass?

    Dataclasses raise ValueError for list, dict and set defaults to prevent all instances sharing one object.
  4. 4. Does the GIL make counter += 1 safe across threads?

    The GIL protects interpreter internals, not your logic. Use a lock or a thread-safe structure.

Summary

  • The MRO is computed by C3; read it from __mro__. super() means "next in the MRO".
  • Class methods build alternative constructors; mutable class attributes are shared by all instances.
  • @dataclass generates __init__, __repr__ and __eq__; use default_factory for mutable defaults.
  • The GIL lets one thread run bytecode at a time: threads for I/O, processes for CPU, asyncio for huge numbers of waits.
  • The GIL does not replace locks for your own shared state.

Next: Python: Classic Coding Questions.