Below are advanced Python interview questions tailored for experienced developers, along with clear and concise answers. These questions cover advanced concepts, best practices, and real-world scenarios that experienced Python developers should be familiar with.
Advanced Python Interview Questions for Experienced Developers
1. What is the Global Interpreter Lock (GIL) in Python?
- Answer: The GIL is a mutex that allows only one thread to execute Python bytecode at a time, even in a multi-threaded program. This means Python threads cannot achieve true parallelism on multi-core CPUs for CPU-bound tasks. However, I/O-bound tasks can still benefit from threading because the GIL is released during I/O operations.
- Workarounds: Use multiprocessing (for CPU-bound tasks) or asynchronous programming (for I/O-bound tasks) to bypass the GIL.
2. What are Python Decorators? Provide an example.
- Answer: Decorators are functions that modify the behavior of other functions or methods. They are often used for logging, access control, memoization, etc. A decorator takes a function as input and returns a new function with added functionality.
- Example:
def my_decorator(func): def wrapper(): print("Something before the function.") func() print("Something after the function.") return wrapper @my_decorator def say_hello(): print("Hello!") say_hello()
Output:Something before the function. Hello! Something after the function.
3. What is the difference between __new__
and __init__
in Python?
- Answer:
__new__
: A static method responsible for creating a new instance of a class. It is called before__init__
and returns the instance.__init__
: An instance method responsible for initializing the newly created instance. It is called after__new__
and does not return anything.
- Example:
class MyClass: def __new__(cls): print("Creating instance") return super().__new__(cls) def __init__(self): print("Initializing instance") obj = MyClass()
Output:Creating instance Initializing instance
4. What are Python Context Managers? Provide an example.
- Answer: Context managers are used to manage resources (e.g., files, database connections) by ensuring proper setup and teardown. They are implemented using the
with
statement and the__enter__
and__exit__
methods. - Example:
class FileManager: def __init__(self, filename, mode): self.filename = filename self.mode = mode def __enter__(self): self.file = open(self.filename, self.mode) return self.file def __exit__(self, exc_type, exc_value, traceback): self.file.close() with FileManager("test.txt", "w") as f: f.write("Hello, World!")
5. What is Metaclass in Python?
- Answer: A metaclass is the class of a class. It defines how a class behaves. By default, Python uses the
type
metaclass to create classes. You can create custom metaclasses by inheriting fromtype
and overriding its__new__
or__init__
methods. - Example:
class Meta(type): def __new__(cls, name, bases, dct): print(f"Creating class {name}") return super().__new__(cls, name, bases, dct) class MyClass(metaclass=Meta): pass # Output: Creating class MyClass
6. What is the difference between deepcopy
and shallow copy
?
- Answer:
- Shallow Copy: Creates a new object but inserts references to the original objects. Changes to mutable objects inside the copy will affect the original.
- Deep Copy: Creates a new object and recursively copies all objects found in the original. Changes to the copy do not affect the original.
- Example:
python import copy list1 = [1, [2, 3]] list2 = copy.copy(list1) # Shallow copy list3 = copy.deepcopy(list1) # Deep copy
7. What is the purpose of asyncio
in Python?
- Answer:
asyncio
is a library for writing asynchronous, single-threaded, concurrent code usingasync
andawait
. It is particularly useful for I/O-bound tasks like network requests or file I/O, where waiting for resources can be non-blocking. - Example:
import asyncio async def fetch_data(): print("Fetching data...") await asyncio.sleep(2) # Simulate I/O operation print("Data fetched!") async def main(): await asyncio.gather(fetch_data(), fetch_data()) asyncio.run(main())
8. What are Python Generators? How are they different from Iterators?
- Answer: Generators are functions that use the
yield
keyword to produce a sequence of values lazily (on-the-fly). Unlike iterators, which require a class with__iter__
and__next__
methods, generators are simpler to implement. - Example:
def my_generator(): yield 1 yield 2 yield 3 for value in my_generator(): print(value)
9. What is Monkey Patching in Python?
- Answer: Monkey patching refers to dynamically modifying or extending classes or modules at runtime. It is useful for testing or fixing bugs but can lead to unexpected behavior if not used carefully.
- Example:
class MyClass: def my_method(self): return "Original" def new_method(self): return "Patched" MyClass.my_method = new_method obj = MyClass() print(obj.my_method()) # Output: Patched
10. What is the difference between multiprocessing
and threading
in Python?
- Answer:
threading
: Uses threads for concurrency. Limited by the GIL, so it is best for I/O-bound tasks.multiprocessing
: Uses separate processes for parallelism. Ideal for CPU-bound tasks as it bypasses the GIL.
- Example:
from multiprocessing import Process def worker(): print("Worker process") p = Process(target=worker) p.start() p.join()
11. What is the purpose of functools.lru_cache
?
- Answer:
lru_cache
is a decorator from thefunctools
module that caches the results of expensive function calls, improving performance by avoiding redundant computations. - Example:
import functools @functools.lru_cache(maxsize=128) def fibonacci(n): if n < 2: return n return fibonacci(n-1) + fibonacci(n-2) print(fibonacci(50)) # Cached for faster computation
12. What is the difference between __slots__
and __dict__
in Python?
- Answer:
__dict__
: A dictionary that stores all attributes of an object. It allows dynamic addition of attributes but consumes more memory.__slots__
: A predefined list of attributes for a class. It reduces memory usage and prevents dynamic attribute creation.
- Example:
class MyClass: __slots__ = ['x', 'y'] obj = MyClass() obj.x = 10 obj.y = 20 # obj.z = 30 # This will raise an AttributeError
13. What is the purpose of collections.defaultdict
?
- Answer:
defaultdict
is a subclass ofdict
that provides a default value for missing keys. It avoidsKeyError
exceptions when accessing non-existent keys. - Example:
from collections import defaultdict my_dict = defaultdict(int) my_dict['a'] += 1 print(my_dict['a']) # Output: 1
14. What is the difference between __getattr__
and __getattribute__
?
- Answer:
__getattr__
: Called only when an attribute is not found in the object’s__dict__
.__getattribute__
: Called for every attribute access, regardless of whether the attribute exists.
- Example:
class MyClass: def __getattr__(self, name): return f"{name} not found" obj = MyClass() print(obj.x) # Output: x not found
15. What is the purpose of itertools
in Python?
- Answer:
itertools
is a module that provides functions for creating iterators for efficient looping. It includes tools likepermutations
,combinations
,product
, andcycle
. - Example:
import itertools for pair in itertools.combinations([1, 2, 3], 2): print(pair)
Certainly! Here are 10 more advanced Python interview questions for experienced developers, along with detailed answers:
16. What is the difference between __call__
and __init__
in Python?
- Answer:
__init__
: Initializes an instance of a class. It is called when an object is created.__call__
: Allows an instance to be called as a function. It is invoked when the instance is called with parentheses.
- Example:
class MyClass: def __init__(self): print("Initialized") def __call__(self): print("Called") obj = MyClass() # Output: Initialized obj() # Output: Called
17. What is the purpose of __mro__
in Python?
- Answer:
__mro__
(Method Resolution Order) is a tuple that defines the order in which base classes are searched when looking for a method or attribute. It is used in multiple inheritance to resolve conflicts. - Example:
class A: pass class B(A): pass class C(A): pass class D(B, C): pass print(D.__mro__) # Output: (<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>)
18. What is the difference between __str__
and __repr__
in Python?
- Answer:
__str__
: Provides a user-friendly string representation of an object, meant for readability.__repr__
: Provides a detailed and unambiguous string representation, often used for debugging.
- Example:
class MyClass: def __str__(self): return "This is __str__" def __repr__(self): return "This is __repr__" obj = MyClass() print(str(obj)) # Output: This is __str__ print(repr(obj)) # Output: This is __repr__
19. What is the purpose of __import__
in Python?
- Answer:
__import__
is a built-in function that dynamically imports a module at runtime. It is rarely used directly; instead, theimportlib.import_module
function is preferred. - Example:
python math_module = __import__('math') print(math_module.sqrt(16)) # Output: 4.0
20. What is the difference between __getitem__
and __setitem__
in Python?
- Answer:
__getitem__
: Allows an object to support indexing (e.g.,obj[key]
).__setitem__
: Allows an object to support item assignment (e.g.,obj[key] = value
).
- Example:
class MyClass: def __init__(self): self.data = {} def __getitem__(self, key): return self.data.get(key, "Not found") def __setitem__(self, key, value): self.data[key] = value obj = MyClass() obj['name'] = 'Alice' print(obj['name']) # Output: Alice print(obj['age']) # Output: Not found
21. What is the purpose of __del__
in Python?
- Answer:
__del__
is a destructor method that is called when an object is about to be destroyed. It is used to perform cleanup actions, such as closing files or releasing resources. - Example:
class MyClass: def __del__(self): print("Object is being deleted") obj = MyClass() del obj # Output: Object is being deleted
22. What is the difference between __enter__
and __exit__
in Python?
- Answer:
__enter__
: Called when entering the context of awith
statement. It returns the resource to be managed.__exit__
: Called when exiting the context of awith
statement. It handles cleanup actions, even if an exception occurs.
- Example:
class FileManager: def __enter__(self): print("Entering context") return self def __exit__(self, exc_type, exc_value, traceback): print("Exiting context") with FileManager() as fm: print("Inside context") # Output: # Entering context # Inside context # Exiting context
23. What is the purpose of __annotations__
in Python?
- Answer:
__annotations__
is a dictionary that stores type hints for variables, function arguments, and return values. It is used for static type checking and documentation. - Example:
def greet(name: str) -> str: return f"Hello, {name}" print(greet.__annotations__) # Output: {'name': <class 'str'>, 'return': <class 'str'>}
24. What is the difference between __subclasshook__
and __instancecheck__
in Python?
- Answer:
__subclasshook__
: Allows a class to define custom behavior for theissubclass()
function.__instancecheck__
: Allows a class to define custom behavior for theisinstance()
function.
- Example:
from abc import ABCMeta class MyMeta(ABCMeta): def __instancecheck__(self, instance): print("Checking instance") return super().__instancecheck__(instance) def __subclasshook__(self, subclass): print("Checking subclass") return True class MyClass(metaclass=MyMeta): pass print(isinstance(MyClass(), MyClass)) # Output: Checking instance, True print(issubclass(MyClass, MyClass)) # Output: Checking subclass, True
25. What is the purpose of __bases__
in Python?
- Answer:
__bases__
is a tuple that contains the base classes of a class. It is used to inspect the inheritance hierarchy. - Example:
class A: pass class B(A): pass print(B.__bases__) # Output: (<class '__main__.A'>,)
26. What is the difference between __dict__
and __weakref__
in Python?
- Answer:
__dict__
: Stores the attributes of an object as a dictionary.__weakref__
: Stores weak references to an object, which do not prevent the object from being garbage collected.
- Example:
class MyClass: pass obj = MyClass() print(obj.__dict__) # Output: {} print(obj.__weakref__) # Output: None
27. What is the purpose of __import__
in Python?
- Answer:
__import__
is a built-in function that dynamically imports a module at runtime. It is rarely used directly; instead, theimportlib.import_module
function is preferred. - Example:
python math_module = __import__('math') print(math_module.sqrt(16)) # Output: 4.0
28. What is the difference between __getattr__
and __getattribute__
in Python?
- Answer:
__getattr__
: Called only when an attribute is not found in the object’s__dict__
.- getattribute`: Called for every attribute access, regardless of whether the attribute exists.
- Example:
class MyClass: def __getattr__(self, name): return f"{name} not found" obj = MyClass() print(obj.x) # Output: x not found
29. What is the purpose of __slots__
in Python?
- Answer:
__slots__
is used to explicitly declare the attributes of a class, reducing memory usage and preventing the creation of a__dict__
for instances. - Example:
class MyClass: __slots__ = ['x', 'y'] obj = MyClass() obj.x = 10 obj.y = 20 # obj.z = 30 # This will raise an AttributeError
30. What is the purpose of __annotations__
in Python?
- Answer:
__annotations__
is a dictionary that stores type hints for variables, function arguments, and return values. It is used for static type checking and documentation. - Example:
def greet(name: str) -> str: return f"Hello, {name}" print(greet.__annotations__) # Output: {'name': <class 'str'>, 'return': <class 'str'>}
These advanced questions and answers should help experienced developers prepare for Python interviews.
*** ALL THE BEST ***
Visit JaganInfo youtube channel for more valuable content https://www.youtube.com/@jaganinfo
Subsection Titles (for Each Question)
- What is the Global Interpreter Lock (GIL) in Python?
- Python Decorators: How Do They Work?
- Metaclasses in Python: What Are They and Why Use Them?
__slots__
vs__dict__
: Which Should You Use?functools.lru_cache
: Boosting Performance with Caching- Generators vs Iterators: What’s the Difference?
threading
vsmultiprocessing
: When to Use Which?asyncio
: Writing Asynchronous Code in Python- Python GIL: Challenges and Solutions
__new__
vs__init__
: Object Creation Explained__call__
: Making Objects Act Like Functions__mro__
: Understanding Method Resolution Orderwith
Statement: Simplifying Resource Management__enter__
and__exit__
: Building Context Managers- Monkey Patching: Modifying Code at Runtime
__import__
: Dynamic Module Loading in Python__getattr__
vs__getattribute__
: Custom Attribute Access__annotations__
: Adding Type Hints to Python Code__str__
vs__repr__
: User-Friendly vs Debugging Output- Singleton Pattern Using Metaclasses
- Factory Pattern with
__new__
- Dependency Injection in Python
__del__
: Cleaning Up Resources with Destructors__bases__
: Inspecting Class Inheritance__weakref__
: Managing Weak References__subclasshook__
and__instancecheck__
: Customizingissubclass
andisinstance
__getitem__
and__setitem__
: Supporting Indexing in Classes__dict__
: Storing Object Attributes__weakref__
: Managing Weak References__annotations__
: Type Hints and Documentation
Tags : Advanced Python Interview Questions, Python Interview Questions for Experienced Developers, Python Advanced Concepts, Python Programming Interview, Python Coding Interview, Python Developer Interview, Python Technical Interview, Python GIL (Global Interpreter Lock), Python Decorators, Python Metaclasses, Python Context Managers, Python Generators, Python asyncio, Python multiprocessing, Python threading, Python functools.lru_cache, Python slots, Python mro, Python call, Python getattr and getattribute, Python annotations, Python import, Python del, Python enter and exit, Python subclasshook and instancecheck, Python bases, Python dict and weakref, Python Interview Preparation for Experienced Developers, Python Interview Tips for Senior Developers, Python Coding Questions for Professionals, Python Interview Cheat Sheet for Experts, Top Advanced Python Interview Questions, Python Interview Questions with Answers, Advanced Python Coding Questions, Python Interview Guide for Experienced Developers, Python Interview Questions for Senior Roles, Python Interview Questions for Tech Leads, Python Memory Management, Python Concurrency and Parallelism, Python Object-Oriented Programming (OOP), Python Dynamic Programming, Python Type Hints and Annotations, Python Asynchronous Programming, Python Design Patterns, Python Best Practices, Learn Advanced Python, Python Programming Tips, Python Coding Examples, Python Interview Practice, Python for Career Growth, Python for Senior Developers,