Advanced 50 Questions • ~12 hrs study

Python Advanced (Q101-150)

Advanced Python concepts — async programming, metaclasses, threading vs multiprocessing, memory optimization, and internals.

101

What is the GIL and how does it affect multithreading?

Short Answer

The Global Interpreter Lock (GIL) is a mutex that allows only one thread to execute Python bytecode at a time. CPU-bound multithreading is ineffective; I/O-bound threading is fine.

  • CPU-bound: Use multiprocessing to bypass GIL
  • I/O-bound: Threading works fine (GIL released during I/O waits)
  • Python 3.13+ experimenting with free-threaded (no-GIL) builds
  • NumPy/C extensions release GIL internally during computation

💡 Memory Trick: "GIL = One cook in the kitchen at a time. More kitchens (processes) = real parallelism"

Follow-up Questions

  • Does asyncio avoid the GIL? (Yes — it's single-threaded)
  • How does concurrent.futures help? (Abstracts threading/multiprocessing)
102

Explain async/await in Python.

Short Answer

async defines a coroutine. await pauses execution until the awaited coroutine completes, allowing other tasks to run. Uses a single-threaded event loop.

import asyncio

async def fetch_data(url):
    await asyncio.sleep(1)  # I/O wait — releases event loop
    return f"Data from {url}"

async def main():
    # Run both concurrently, not sequentially
    results = await asyncio.gather(
        fetch_data("api/users"),
        fetch_data("api/posts"),
    )
    print(results)

asyncio.run(main())

💡 Memory Trick: "async = 'I might pause' | await = 'pause here until done'"

103

What are metaclasses in Python?

Short Answer

A metaclass is a class of a class. It defines how classes are created. Default metaclass is type. Use them to enforce interfaces, auto-register subclasses, or validate class definitions.

class ValidateMeta(type):
    def __new__(mcs, name, bases, namespace):
        if 'run' not in namespace:
            raise TypeError(f"{name} must implement 'run' method")
        return super().__new__(mcs, name, bases, namespace)

class Pipeline(metaclass=ValidateMeta):
    def run(self):  # Required — metaclass enforces this
        pass

💡 Memory Trick: "Metaclass = Factory that builds classes (just as a class is a factory that builds objects)"

104

Threading vs Multiprocessing vs Asyncio — when to use what?

Approach Best For GIL? Memory
ThreadingI/O-bound (file, network)AffectedShared
MultiprocessingCPU-bound (ML training)BypassedSeparate
AsyncioMany concurrent I/O tasksN/AShared

💡 Memory Trick: "Thread = shared kitchen | Process = separate kitchens | Async = one chef multitasking"

Questions 105-150 continue in the full documentation.

Topics: Context Managers, Descriptors, __slots__, Weak References, Memory Profiling, Type Hints (Protocol, TypeVar, Generics), importlib, and more.

View Full Documentation →