Interview Questions

30 Python Common Interview Questions and Answers

Author: Interview Questions Posted 15 days ago 42 min read

10 More Python Common Interview Questions and Answers (Part 3). Wrapping up our comprehensive interview prep series, here are 10 advanced Python interview questions covering memory optimization, object-oriented internals, concurrency, and architecture.


21. What are __slots__ and why are they used?

By default, Python instances store their attributes in a dynamic dictionary named __dict__. While flexible, dictionaries consume significant memory overhead.

Defining __slots__ in a class tells Python to allocate a fixed, static array for a pre-determined set of attributes instead of a __dict__.

  • Benefits: Drastically reduces memory consumption for classes with millions of instances and can slightly speed up attribute access.
  • Limitations: You cannot dynamically add new attributes to an instance unless they are listed in __slots__.
class SlottedClass:
    __slots__ = ['name', 'age']  # Restricts attributes to only these two

    def __init__(self, name, age):
        self.name = name
        self.age = age

obj = SlottedClass("Alice", 30)
# obj.email = "[email protected]"  # Raises AttributeError: 'SlottedClass' object has no attribute 'email'


22. What is a context manager and how do you implement one?

A context manager is an object that controls the environment within a with statement block, typically handling setup and teardown tasks (like opening and closing files or database connections).

You can implement a context manager in two ways:

  1. Using a class with __enter__ and __exit__ magic methods.
  2. Using a generator combined with the @contextmanager decorator from the contextlib module.
from contextlib import contextmanager

@contextmanager
def managed_resource():
    print("Setup: Acquiring resource...")
    try:
        yield "Resource is ready"
    finally:
        print("Teardown: Releasing resource...")

with managed_resource() as res:
    print(res)
# Output:
# Setup: Acquiring resource...
# Resource is ready
# Teardown: Releasing resource...


23. What is the difference between @staticmethod, @classmethod, and a regular instance method?

  • Instance Method: The default method type. It takes self as the first argument and has access to instance and class attributes.
  • Class Method (@classmethod): Takes cls as the first argument instead of self. It can modify or access class-level state and is frequently used as an alternative constructor.
  • Static Method (@staticmethod): Takes neither self nor cls. It behaves like a regular function that happens to live inside a class namespace, useful for utility logic that doesn't depend on class or instance state.
class MyClass:
    class_variable = "Shared"

    def instance_method(self):
        return "Regular instance method"

    @classmethod
    def class_method(cls):
        return f"Class method accessing {cls.class_variable}"

    @staticmethod
    def static_method():
        return "Static utility method"


24. What are Abstract Base Classes (ABCs)?

An Abstract Base Class (ABC) defines a common interface for a set of subclasses, enforcing that they implement specific methods. You cannot instantiate an ABC directly.

Python provides the abc module for this purpose. If a subclass fails to implement any abstract methods marked with @decorator, Python will raise a TypeError when attempting to instantiate it.

from abc import ABC, abstractmethod

class PaymentGateway(ABC):
    @abstractmethod
    def process_payment(self, amount):
        pass

class StripeGateway(PaymentGateway):
    def process_payment(self, amount):
        print(f"Processing ${amount} via Stripe")

# gateway = PaymentGateway()  # TypeError: Can't instantiate abstract class
stripe = StripeGateway()      # Works fine


25. How does asynchronous programming work in Python (asyncio)?

Python's asyncio framework uses an event loop to achieve concurrency in a single thread using coroutines (async/def and await).

Unlike multi-threading (which is bound by the GIL for CPU tasks), asynchronous programming excels at I/O-bound tasks (like web scraping, database queries, or handling network requests). While one task is waiting for a network response, the event loop pauses it and switches to execute other active tasks.

import asyncio

async def fetch_data():
    print("Fetching data...")
    await asyncio.sleep(1)  # Simulates network I/O
    print("Data received!")
    return {"data": 123}

async def main():
    result = await fetch_data()
    print(result)

# asyncio.run(main())


26. What is "Name Mangling" in Python?

Name mangling is a mechanism Python uses to protect class-private attributes from accidental modification or overriding in subclasses.

Any identifier prefixed with two leading underscores and at most one trailing underscore (e.g., __variable) inside a class definition is automatically transformed at compile-time to _ClassName__variable.

class SecretHolder:
    def __init__(self):
        self.__secret = "my_password"

s = SecretHolder()
# print(s.__secret)  # Raises AttributeError
print(s._SecretHolder__secret)  # "my_password" (accessible via mangled name)


27. What is a closure in Python?

A closure is a nested function that remembers and has access to variables from its enclosing outer scope, even after the outer function has finished execution and returned.

For a closure to exist, three conditions must be met:

  1. There must be a nested function.
  2. The nested function must refer to a value defined in the enclosing function.
  3. The enclosing function must return the nested function.
def outer_func(msg):
    message = msg
    def inner_func():
        print(f"Message is: {message}")
    return inner_func

my_closure = outer_func("Hello, World!")
my_closure()  # Prints "Message is: Hello, World!" even though outer_func has finished


28. What is a Python descriptor?

A descriptor is an object that controls attribute access for other classes. Specifically, any object that defines at least one of these magic methods is considered a descriptor:

  • __get__(self, instance, owner)
  • __set__(self, instance, value)
  • __delete__(self, instance)

Descriptors are the underlying mechanism that power advanced Python features like @property, staticmethod, classmethod, and functools.cached_property.

class ValidatedString:
    def __set_name__(self, owner, name):
        self.name = name

    def __get__(self, instance, owner):
        return instance.__dict__.get(self.name)

    def __set__(self, instance, value):
        if not isinstance(value, str):
            raise TypeError(f"{self.name} must be a string")
        instance.__dict__[self.name] = value

class User:
    username = ValidatedString()

u = User()
# u.username = 123  # Raises TypeError: username must be a string
u.username = "python_dev"  # Works perfectly


29. What are Type Hints and why are they useful?

Introduced in PEP 484, type hints allow developers to explicitly specify the expected data types for function arguments, return values, and variables.

  • Why they are useful: They do not enforce types at runtime (Python remains dynamically typed), but they greatly improve code readability, documentation, and enable static analysis tools (like mypy or IDE linters) to catch type-mismatch bugs before code runs.
def calculate_area(radius: float) -> float:
    return 3.14159 * (radius ** 2)


30. What is serialization/pickling in Python and what are its risks?

Pickling is Python's built-in module (pickle) used to serialize (convert Python objects into a byte stream) and deserialize (reconstruct objects from bytes) data. It allows you to save complex states to disk.

  • The Security Risk: Never unpickle data from an untrusted or unauthenticated source. The pickle format can execute arbitrary code during unpickling, making it vulnerable to Remote Code Execution (RCE) attacks. For untrusted data, use secure formats like JSON instead.