Advanced Python Questions

Deep dives into internals and advanced features.

1. What is the Global Interpreter Lock (GIL)?

Answer: The GIL is a mutex that protects access to Python objects, preventing multiple threads from executing Python bytecodes at once. This means that in CPython, multi-threading is not suitable for CPU-bound tasks, only for I/O-bound tasks.

2. Explain Generators and the `yield` keyword.

Answer: Generators are functions that return an iterable set of items, one at a time, in a special way. When an iteration over a set of items starts using the for statement, the generator is run. Once the generator's function code reaches a "yield" statement, the generator yields its execution back to the for loop, returning a new value from the set.

Benefit: Memory efficiency (lazy evaluation).

3. What are Metaclasses?

Answer: A metaclass is a class of a class. A class defines how an instance of the class behaves, while a metaclass defines how a class behaves. A class is an instance of a metaclass.

In Python, everything is an object, including classes. type is the default metaclass.

4. What is the difference between `__new__` and `__init__`?

Answer:

5. What are Decorators?

Answer: Decorators are a design pattern in Python that allows a user to add new functionality to an existing object without modifying its structure. They are usually called before the definition of a function you want to decorate.

def my_decorator(func):
    def wrapper():
        print("Something is happening before the function is called.")
        func()
        print("Something is happening after the function is called.")
    return wrapper

@my_decorator
def say_hello():
    print("Hello!")

6. Explain Context Managers and the `with` statement.

Answer: Context managers allow you to allocate and release resources precisely when you want to. The most widely used example of context managers is the with statement.

They are implemented using the __enter__ and __exit__ methods.

with open('file.txt', 'w') as f:
    f.write('hello world')
# File is automatically closed here, even if an exception occurs.

7. What is Monkey Patching?

Answer: Monkey patching refers to dynamic modifications of a class or module at runtime. It is often used to replace a method or attribute with a mock or stub during testing.

Caution: It should be used sparingly as it can lead to code that is hard to debug and maintain.

8. What are Descriptors?

Answer: Descriptors are Python objects that implement a method of the descriptor protocol: __get__, __set__, or __delete__. They provide a powerful way to control attribute access.

Properties (@property), methods, static methods, and class methods are all based on the descriptor protocol.