Q: Explain the concept of metaclasses in Python.
A: Metaclasses are classes that create other classes. They are used to customize class creation behavior, such as adding custom attributes or methods to all instances of a class.
Python
class MyMetaclass(type):
def __new__(cls, name, bases, attrs):
attrs['custom_attribute'] = 'value'
return super().__new__(cls, name, bases, attrs)
class MyClass(metaclass=MyMetaclass):
pass
obj = MyClass()
print(obj.custom_attribute) # Output: value
Use code with caution.
Q: What is the difference between shallow and deep copying in Python?
A: Shallow copy: Creates a new object but references the same underlying data. Deep copy: Creates a new object and recursively copies all data.
Python
import copy
original_list = [1, 2, [3, 4]]
shallow_copy = copy.copy(original_list)
shallow_copy[0] = 5
print(original_list) # Output: [5, 2, [3, 4]]
Use code with caution.
deep_copy = copy.deepcopy(original_list)
deep_copy[0] = 5
print(original_list) # Output: [1, 2, [3, 4]]
Use code with caution.
Q: How can you optimize Python code for performance?
A: Use efficient data structures, avoid unnecessary computations, profile your code, and consider using libraries like Cython or Numba.
Data Structures and Algorithms
Q: Implement a binary search algorithm in Python.
Python
def binary_search(arr, x):
low = 0
high = len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == x:
return mid
elif arr[mid] < x:
low = mid + 1
else:
high = mid - 1
return -1 # Element not found
Q: Explain the concept of a heap data structure and its applications in Python.
A: A heap is a complete binary tree where each node is greater than or equal to (in a max heap) or less than or equal to (in a min heap) its children. Applications include priority queues, heap sort, and graph algorithms.
Python Libraries and Frameworks
Q: What are some common use cases for the NumPy library?
A: Numerical computing, data analysis, and scientific computing. Operations on arrays and matrices. Mathematical functions and linear algebra. Random number generation.
Q: Explain the concept of object-relational mapping (ORM) and its benefits in Python.
A: ORMs like SQLAlchemy map database tables to Python classes, making it easier to interact with databases. Benefits include simplified database interactions, reduced boilerplate code, and improved code maintainability.
Q: What are some common design patterns used in Python?
A: Singleton, Factory, Observer, Decorator.
Advanced Python Topics
Q: How do you create custom context managers in Python?
A: Use the with statement and the __enter__ and __exit__ methods.
Python
class MyResource:
def __enter__(self):
print("Entering resource")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print("Exiting resource")
with MyResource() as resource:
print("Using resource")
Use code with caution.
Q: Explain the concept of coroutines and their use cases in Python.
A: Coroutines are functions that can be paused and resumed, allowing for non-blocking operations and asynchronous programming. Use cases include asynchronous I/O, long-running tasks, and creating custom generators.
Q: What is the difference between generators and regular functions?
A: Generators use the yield keyword to return values one at a time, preserving state between calls. Regular functions return a single value at the end of execution.
Python
def my_generator():
for i in range(5):
yield i
for num in my_generator():
print(num)
Use code with caution.
Python Best Practices
Q: What are some best practices for writing clean and maintainable Python code?
A: Follow PEP 8 style guidelines, use meaningful variable and function names, write clear and concise comments, break down complex logic into smaller functions, and use version control.
Q: How do you handle memory management in Python?
A: Python’s garbage collector automatically handles memory management, but understanding concepts like reference counting is helpful. Avoid creating unnecessary objects and large data structures.
Q: What are some common Python anti-patterns to avoid?
A: Global variables, excessive nesting, magic numbers, overly complex code.
Q: How do you test your Python code?
A: Use unit testing frameworks like unittest or pytest, write comprehensive test cases, and consider different scenarios and edge cases.