Advanced Python Interview Questions: Internals (2027)

44 advanced Python interview questions on internals: GIL and free-threading in 3.14, descriptors, metaclasses, MRO, asyncio, memory and t-strings.

Sep 5, 2025 - 18:03
Nov 5, 2026 - 21:50
 0  68
TOPICInterview Q & APractical guide
Advanced Python Interview Questions: Internals (2027)

Advanced Python interview questions test how the language works underneath: the GIL and the free-threaded build, descriptors, metaclasses, the method resolution order, generators, asyncio, memory management and the newer features in Python 3.12 to 3.14. Strong answers explain the mechanism, then show a short example and a trade-off. This page has 44 questions focused on language internals, grouped by level, with scenario questions at the end.

It is the "how Python works" companion to our other Python guides. For practical problems, see scenario-based Python interview questions for DevOps; for coding exercises, see Python coding interview questions with solutions; and for production engineering topics, see Python engineer interview questions for experienced candidates.

Key takeaways

  • Python 3.14 was released on 7 October 2025. Its free-threaded build (no GIL) is now officially supported under PEP 779, but the default build still has the GIL.
  • Annotations in 3.14 are evaluated lazily (PEP 649 and PEP 749), and template string literals t"..." arrive through PEP 750.
  • The incremental garbage collector shipped in 3.14.0 was reverted to the 3.13 generational collector in 3.14.5, according to the official What's New page.
  • Descriptors explain how properties, methods, staticmethod and classmethod work. If you can explain descriptors, many other answers follow.
  • Interviewers at senior level look for trade-offs: threads vs processes vs asyncio vs subinterpreters, and when a metaclass is the wrong tool.

Topic map

AreaTypical questionsLevel
Object modelEverything is an object, identity vs equality, mutabilityFreshers
FunctionsClosures, decorators, *args/**kwargs, default argument trapFreshers
ClassesMRO, super(), descriptors, __slots__, metaclasses2-5 years
ConcurrencyGIL, free-threading, asyncio, multiprocessing, subinterpreters2-5 years and senior
RuntimeReference counting, cyclic GC, bytecode, importsSenior

Freshers: object model and functions

1. What does "everything is an object" mean in Python?

Integers, functions, classes and modules are all objects with a type, an identity and a value. You can pass a function as an argument, store a class in a list, or add attributes to a module at runtime. Even type is an object whose type is type.

2. What is the difference between is and ==?

is checks identity: whether two names point to the same object. == checks equality by calling __eq__. Use is for singletons such as None, and == for values. Small integer caching can make is look like it works on numbers, but that is an implementation detail.

3. Why is a mutable default argument a bug?

Default values are evaluated once, when the function is defined. A list default is shared between calls, so items pile up. Use None and create the list inside the function.

def add_tag(tag, tags=None):
    if tags is None:
        tags = []
    tags.append(tag)
    return tags

4. What is a closure?

A closure is an inner function that remembers variables from the enclosing function's scope after the outer function has returned. The values live in cell objects visible through __closure__. Use nonlocal to rebind such a variable from the inner function.

5. How does a decorator work?

A decorator is a callable that takes a function and returns a replacement. @timer above def f is the same as f = timer(f). Use functools.wraps so the wrapper keeps the original name, docstring and signature metadata.

import functools, time

def timer(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        try:
            return func(*args, **kwargs)
        finally:
            print(f"{func.__name__} took {time.perf_counter() - start:.3f}s")
    return wrapper

6. How do you write a decorator that takes arguments?

Add one more layer: an outer function takes the arguments and returns the actual decorator. @retry(times=3) first calls retry(times=3), and the result decorates the function.

7. What is the difference between an iterable and an iterator?

An iterable has __iter__ and can produce an iterator, like a list. An iterator has __next__ and also returns itself from __iter__; it is consumed as you loop. Calling iter() on a list gives a fresh iterator each time.

8. What does a generator do differently from a function?

A function with yield returns a generator object instead of running to completion. Each next() resumes execution until the next yield, keeping local state between calls. This lets you process large files or streams without loading everything into memory.

9. What is yield from?

It delegates to a sub-iterator or sub-generator, passing values, send() calls and exceptions through, and it evaluates to the sub-generator's return value. It simplifies writing generators that compose other generators.

10. What is a context manager?

An object with __enter__ and __exit__ used by with. __exit__ runs even when an exception occurs, which makes it the standard way to release files, locks and connections. contextlib.contextmanager builds one from a generator.

11. What is LEGB?

The order Python uses to resolve a name: Local, Enclosing function scopes, Global (module) and Built-in. Assigning to a name inside a function makes it local unless you declare it global or nonlocal.

12. Shallow copy vs deep copy?

copy.copy creates a new outer container but shares the inner objects. copy.deepcopy recursively copies inner objects too, tracking already-copied objects to handle cycles. Classes can control the behaviour with __copy__ and __deepcopy__.

2-5 years: classes, descriptors and concurrency

13. What is the method resolution order?

The MRO is the order Python searches base classes for an attribute. CPython computes it with the C3 linearisation algorithm, which keeps each class before its parents and keeps the order of bases you listed. Inspect it with ClassName.__mro__.

14. What does super() actually call?

It calls the next class in the MRO of the instance's type, not necessarily the direct parent. In cooperative multiple inheritance every class calls super() so that each class in the chain runs once.

15. What is a descriptor?

An object that defines __get__, and optionally __set__ or __delete__, and is stored as a class attribute. Attribute access on instances then calls those methods. property, functions (which become bound methods), staticmethod and classmethod are all descriptors.

16. Data descriptor vs non-data descriptor?

A data descriptor defines __set__ or __delete__ and takes priority over the instance dictionary. A non-data descriptor defines only __get__, so a value in the instance __dict__ wins. That is why you can shadow a method on an instance but not a property.

class Positive:
    def __set_name__(self, owner, name):
        self.name = "_" + name
    def __get__(self, obj, objtype=None):
        return getattr(obj, self.name)
    def __set__(self, obj, value):
        if value <= 0:
            raise ValueError("must be positive")
        setattr(obj, self.name, value)

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

17. What does __set_name__ do?

Python calls it on each descriptor when the owning class is created, passing the owner class and the attribute name. It lets a descriptor know its own name without repeating it, as in the example above.

18. What is __slots__ for?

Declaring __slots__ tells Python to store a fixed set of attributes in a compact structure instead of a per-instance __dict__. It reduces memory for many small objects and blocks accidental new attributes. Each class in an inheritance chain must declare its own slots to keep the benefit.

19. __getattr__ vs __getattribute__?

__getattribute__ runs on every attribute access. __getattr__ runs only when normal lookup fails. Override __getattr__ for fallbacks such as proxies; overriding __getattribute__ is rarely needed and easy to make recursive.

20. What is a metaclass?

A metaclass is the class of a class. type is the default. A custom metaclass, usually a subclass of type, can change how classes are created, for example by registering them or validating attributes. ORMs and plugin systems use them.

21. When should you avoid a metaclass?

Most needs are met by class decorators or __init_subclass__, which are simpler and do not conflict when combining base classes. Two bases with unrelated metaclasses raise a metaclass conflict, which is one more reason to prefer the lighter tools.

class Plugin:
    registry = {}
    def __init_subclass__(cls, name, **kwargs):
        super().__init_subclass__(**kwargs)
        Plugin.registry[name] = cls

class S3Upload(Plugin, name="s3"):
    pass

22. What are abstract base classes?

Classes created with abc.ABC that mark methods with @abstractmethod. You cannot instantiate a subclass until it implements them all. collections.abc defines standard interfaces like Mapping and Iterable.

23. Protocols vs ABCs?

typing.Protocol supports structural typing: a class matches if it has the right methods, without inheriting. Type checkers use protocols statically; add @runtime_checkable if you need isinstance checks at runtime, which only check method presence.

24. What is the GIL?

The Global Interpreter Lock in the default CPython build lets only one thread run Python bytecode at a time. It simplifies memory management through reference counting. Threads still help with I/O, because blocking calls release the lock, but CPU-bound pure-Python code does not speed up with threads in the default build.

25. What is the free-threaded build?

A separate CPython build without the GIL, introduced experimentally in 3.13 (PEP 703) and officially supported from 3.14 (PEP 779). Threads can run Python code in parallel on multiple cores. The What's New page puts the single-threaded slowdown at roughly 5 to 10 percent, depending on platform and compiler. C extensions must declare support, so check your dependencies.

26. Does removing the GIL make code thread-safe?

No. Even with the GIL, counter += 1 is several bytecode steps and can lose updates between threads. Shared mutable state still needs a threading.Lock, a queue or another synchronisation tool, with or without free-threading.

27. Threads, processes, asyncio: how do you choose?

Use asyncio for many concurrent network operations in one thread. Use threads for blocking I/O with libraries that are not async. Use multiprocessing or ProcessPoolExecutor for CPU-bound work in the default build. On the free-threaded build, threads become an option for CPU-bound work too.

28. What are subinterpreters in Python 3.14?

PEP 734 added the concurrent.interpreters module, which runs multiple isolated interpreters in one process, each with its own GIL. concurrent.futures.InterpreterPoolExecutor provides a pool of them. The docs note current limits, including slow startup, higher memory use and limited object sharing.

29. How does the asyncio event loop work?

A single thread runs the loop, which schedules coroutines. When a coroutine hits await on something not ready, it yields control and the loop runs another task. Any blocking call inside a coroutine stops the whole loop; push such calls to asyncio.to_thread.

30. asyncio.gather vs TaskGroup?

asyncio.TaskGroup, added in 3.11, gives structured concurrency: if one task fails, the others are cancelled and errors are raised together as an ExceptionGroup. gather is older and, by default, does not cancel siblings on failure.

import asyncio

async def fetch(n):
    await asyncio.sleep(0.1)
    return n * 2

async def main():
    async with asyncio.TaskGroup() as tg:
        tasks = [tg.create_task(fetch(i)) for i in range(5)]
    print([t.result() for t in tasks])

asyncio.run(main())

31. What are exception groups and except*?

Added in 3.11 (PEP 654), an ExceptionGroup carries several exceptions at once, as concurrent tasks can fail together. except* handles matching exceptions from the group and lets the rest propagate.

Senior: runtime and memory

32. How does CPython manage memory?

Mainly through reference counting: each object counts references and is freed when the count reaches zero. A cyclic garbage collector finds groups of objects that refer to each other but are unreachable. Small objects come from CPython's own allocator, pymalloc.

33. What happened to the incremental garbage collector in 3.14?

Python 3.14.0 shipped an incremental collector. The official What's New page says it was reverted to the 3.13 generational collector in 3.14.5 after reports of significant memory pressure in production. This is a good example of checking the patch version when someone quotes a feature.

34. How do you find a memory leak in a Python service?

Take tracemalloc snapshots at intervals and compare them to see which lines allocate growing memory. Look for unbounded caches, global lists, and reference cycles holding large objects. gc.get_referrers helps trace who keeps an object alive.

35. What does weakref solve?

A weak reference does not increase the reference count, so the object can still be freed. Caches built on WeakValueDictionary or observers stored as weak references avoid keeping objects alive by accident.

36. What is bytecode and how do you inspect it?

CPython compiles source to bytecode instructions that its interpreter executes. The dis module shows them. Since 3.11 the interpreter specialises instructions at runtime for common types (PEP 659), which is part of why newer versions run faster.

37. How does the import system find a module?

Python checks sys.modules first, then asks the finders on sys.meta_path, which search sys.path entries. A loader then executes the module code once and caches it. This is why a local file named like a standard module can shadow it.

38. What changed with annotations in Python 3.14?

Under PEP 649 and PEP 749, annotations are no longer evaluated when the function or class is defined. They are stored and evaluated when requested, and the new annotationlib module can return them as values, forward references or strings. Forward references no longer need to be quoted.

39. What are template strings (t-strings)?

PEP 750, new in 3.14, adds t"..." literals. Unlike f-strings, they produce a string.templatelib.Template object that keeps the static text and interpolated values separate, so a library can escape values before building the final string, for example for HTML or SQL.

40. What is the type parameter syntax from 3.12?

PEP 695 lets you write generics directly: def first[T](items: list[T]) -> T and class Box[T]:, plus the type statement for aliases. It replaces most manual TypeVar declarations.

Scenario questions

41. A CPU-heavy log parser is slow with 8 threads. What do you do?

Profile first with cProfile to confirm the time is in Python code. On the default build, switch to ProcessPoolExecutor and send work in chunks to reduce pickling overhead. If dependencies support it, test the free-threaded build or InterpreterPoolExecutor, and measure before choosing.

42. An async API server freezes under load. How do you find the cause?

Look for blocking calls inside coroutines, such as requests, time.sleep or heavy JSON parsing. Run with PYTHONASYNCIODEBUG=1 or loop.set_debug(True), which logs slow callbacks. Replace blocking libraries with async ones or move the work to asyncio.to_thread.

43. A service's memory grows for days and then it restarts. What is your approach?

Reproduce in staging, compare tracemalloc snapshots over time, and check caches such as functools.lru_cache without a maxsize. Check the exact Python patch version too, given the 3.14 garbage collector change. Then fix the source and add a memory metric with an alert.

44. A team wants a metaclass to auto-register plugins. What do you recommend?

Suggest __init_subclass__ instead: it registers subclasses with less code, no metaclass conflicts, and is easier for the next developer to read. Keep metaclasses for cases that need to change class creation itself.

How to prepare

Read the Descriptor HOWTO and the What's New pages for 3.12, 3.13 and 3.14, then write small experiments for each answer above. Use dis, tracemalloc and cProfile on your own scripts so you can talk about real output. If Python is part of a DevOps role, the DevOps training in Pune (Kharadi classroom and live online) covers Python automation alongside CI/CD and cloud. Freshers should start with Python interview questions for freshers and the broader 150+ Python questions for DevOps.

FAQ

Is the GIL removed in Python 3.14?

Not in the default build. Python 3.14 officially supports a separate free-threaded build without the GIL (PEP 779). The standard build you download by default still has the GIL.

What topics count as advanced Python?

Descriptors, metaclasses, the MRO, generators and coroutines, asyncio, the GIL and free-threading, memory management, the import system and typing features such as protocols and generics.

Do DevOps engineers need advanced Python?

Most DevOps roles need solid scripting, error handling, and some concurrency. Senior roles that build internal tools or platform services often ask about asyncio, packaging and performance.

What is the difference between a descriptor and a property?

property is a built-in descriptor. Writing your own descriptor class lets you reuse the same validation or behaviour across many attributes and classes.

Should I learn metaclasses for interviews?

Know what they are and when to use them, but also know the simpler alternatives: class decorators and __init_subclass__. Interviewers often want to hear that you would avoid a metaclass when possible.

What are t-strings in Python?

Template string literals added in 3.14 by PEP 750. They return a Template object instead of a string, so code can process interpolated values safely before producing output.

Which Python version should I prepare with?

Use a current release such as 3.14 and know what changed in 3.12, 3.13 and 3.14, since interviewers often ask about recent features and the GIL work.

Official references

Interested in learning more?Get a callback from our training advisors.

What's Your Reaction?

Like Like 0
Dislike Dislike 0
Love Love 0
Funny Funny 0
Angry Angry 0
Sad Sad 0
Wow Wow 0
Mridul I am a passionate technology enthusiast with a strong focus on DevOps, Cloud Computing, and Cybersecurity. Through my blogs at DevOps Training Institute, I aim to simplify complex concepts and share practical insights for learners and professionals. My goal is to empower readers with knowledge, hands-on tips, and industry best practices to stay ahead in the ever-evolving world of DevOps.