These are the questions that actually decide Python Developer interviews in India — practice answering out loud before your next round.
Q1.How does the Global Interpreter Lock (GIL) work in CPython, and what are the implications of PEP 703 (free-threaded Python) in Python 3.13?
The Global Interpreter Lock (GIL) is a mutual exclusion lock used by CPython to prevent race conditions during memory management, ensuring that only one native OS thread executes Python bytecode at any given moment. This prevents CPU-bound multithreading from scaling across multiple CPU cores. PEP 703 introduced in Python 3.13 provides an experimental free-threaded build that eliminates the GIL by replacing global reference counting with mimalloc thread-safe memory allocators, biased reference counting, and immortal objects. In legacy Python, CPU parallelism requires the multiprocessing module or C extensions, whereas I/O parallelism is cleanly handled by threading or asyncio.
Q2.Explain how Python's asyncio event loop executes tasks, and contrast it with multithreading and multiprocessing for I/O vs CPU-bound tasks.
Python's asyncio implements cooperative multitasking on a single OS thread using an event loop and generators/coroutines. When a coroutine awaits an asynchronous I/O operation (e.g. await db.fetch()), it yields control back to the event loop, which selects and executes another runnable task from its queue without thread context-switching overhead. For I/O-bound tasks (database queries, HTTP calls, socket reads), asyncio provides massive concurrency handling tens of thousands of connections with minimal memory. For CPU-bound tasks (cryptography, image processing, complex data transformation), asyncio blocks the single thread; such work must be offloaded to concurrent.futures.ProcessPoolExecutor to leverage multiple hardware cores.
Q3.How does Python handle memory management and garbage collection: contrast reference counting with the generational cyclic GC.
Memory management in CPython utilizes two complementary mechanisms: (1) Reference Counting: Every Python object possesses an internal ob_refcnt counter. Whenever an object is referenced, the counter increments; when a reference is deleted or goes out of scope, it decrements. When ob_refcnt reaches 0, the object's memory is deallocated immediately. (2) Generational Cyclic Garbage Collector: Reference counting cannot detect reference cycles (e.g. Object A references B, and B references A). The gc module categorizes objects into three generations (Gen 0, 1, 2) based on survival age. Gen 0 is inspected frequently for cyclic references using pointer traversal; surviving objects graduate to Gen 1 and eventually Gen 2, ensuring thorough cleanup of circular graphs.
Q4.What are Python generators and how does yield from optimize memory when streaming multi-gigabyte files or database cursors?
Generators are functions containing the yield keyword that return an iterator object implementing the __iter__ and __next__ protocols. Instead of computing an entire collection in memory and returning a list, a generator produces values lazily on-demand, maintaining its local execution state and stack frame between iterations. Memory consumption remains constant (O(1)) regardless of whether processing 100 rows or 100 million rows. The yield from subgen syntax delegates iteration directly to a sub-generator, establishing a bidirectional channel that automatically forwards values, exceptions, and return values without boilerplate while loops.
Q5.Explain Python's descriptor protocol (__get__, __set__, __delete__) and how property and ORM field mappings are built upon it.
A descriptor is any object that implements at least one of the methods in the descriptor protocol: __get__(self, obj, type=None), __set__(self, obj, value), or __delete__(self, obj). When an attribute access occurs on an instance (e.g. instance.attr), Python's attribute lookup checks the class dictionary. If attr is a descriptor, Python executes descriptor.__get__(instance, type) instead of returning the raw value. The built-in @property decorator is a descriptor that wraps getter, setter, and deleter functions. ORMs like SQLAlchemy and Django use descriptors to define model fields: accessing model.user_id triggers SQL queries, type coercion, dirty tracking, and validation dynamically.
Q6.How do metaclasses work in Python, and how does __init_subclass__ provide a cleaner modern alternative for class registration?
In Python, classes themselves are instances of metaclasses (default is type). A custom metaclass inherits from type and intercepts class creation via __new__(mcs, name, bases, namespace), allowing metaprogramming such as automated method registration, attribute validation, or dynamic method generation before the class object is instantiated. However, metaclasses introduce inheritance complexity and metaclass conflicts. Python 3.6 introduced __init_subclass__(cls, **kwargs), which is invoked automatically whenever a parent class is subclassed. This allows parent classes to inspect, register, and validate their children cleanly using standard inheritance without needing a separate metaclass.
Q7.Why is Pydantic v2 significantly faster than v1, and how does its Rust-based pydantic-core serialize and validate data structures?
Pydantic v1 was written in pure Python, where recursive dictionary parsing, type coercion, and schema validation incurred massive Python interpreter function-call overhead. Pydantic v2 re-architected its core validation and serialization engine into pydantic-core, written in Rust. In v2, Python builds a validation schema graph during model declaration, compiles it into a Rust struct, and executes all parsing, type coercion, JSON parsing (via jiter), and validation in compiled Rust machine code. Data serialization to JSON occurs directly in Rust without traversing intermediate Python objects, achieving 5x to 50x performance improvements across APIs.
Q8.How do you profile and diagnose memory leaks in a long-running Python production service using tracemalloc and objgraph?
Diagnosing Python memory leaks involves: (1) tracemalloc: Enable with tracemalloc.start(), take memory snapshots at different time intervals (snapshot1 = tracemalloc.take_snapshot()), and compare them via snapshot2.compare_to(snapshot1, 'lineno'). This isolates the exact Python source file and line number allocating growing blocks of RAM. (2) objgraph: Inspect live in-memory objects with objgraph.show_most_common_types() to identify objects that are failing to deallocate. Call objgraph.show_backrefs() to render visual graphviz diagrams revealing which global variables, caches, or cyclic references are keeping dead instances pinned in memory.