Monday, April 21, 2025

Advanced Python Questions

1. What are Python decorators and how do they work?

Answer: Decorators are functions that modify the behavior of other functions or methods. They are used with @decorator_name syntax.

def decorator(func):
    def wrapper():
        print("Before function call")
        func()
        print("After function call")
    return wrapper

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

say_hello()

---

2. What is the difference between is and == in Python?

Answer:

is checks object identity (whether two variables point to the same object in memory).

== checks value equality (whether the values are the same).


a = [1, 2]
b = [1, 2]
print(a == b)  # True
print(a is b)  # False
---

3. What is a generator? How is it different from a list?

Answer:
Generators yield items one at a time using yield. They are memory-efficient and lazy-evaluated.

def gen():
    yield 1
    yield 2

g = gen()
print(next(g))  # 1

Generators don’t store the whole list in memory, unlike a normal list.
---

4. Explain Python's GIL (Global Interpreter Lock).

Answer:
The GIL is a mutex in CPython that allows only one thread to execute at a time, even on multi-core systems. This affects multi-threaded CPU-bound programs but not I/O-bound ones.
---

5. What are metaclasses in Python?

Answer:
Metaclasses are classes of classes — they define how classes behave. You can control class creation using metaclasses.

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

---

6. How does *args and **kwargs work?

Answer:

*args captures positional arguments as a tuple.

**kwargs captures keyword arguments as a dict.

def func(*args, **kwargs):
    print(args)
    print(kwargs)

func(1, 2, a=3, b=4)

---

7. What are closures in Python?

Answer:
Closures are functions that remember the values from their enclosing scope even if the outer function has finished executing.

def outer(x):
    def inner():
        print(x)
    return inner

closure = outer(10)
closure()  # 
---

8. What is monkey patching in Python?

Answer:
Changing or extending code at runtime, typically used in testing.

import math
math.sqrt = lambda x: "patched"
print(math.sqrt(9))  # patched

9. How does Python’s memory management work?

Answer:

Python uses reference counting and a garbage collector for cyclic references.

Memory is managed in private heaps.

10. Difference between shallow and deep copy?

Answer:

Shallow copy: copies only references for nested objects.

Deep copy: copies all levels recursively.

import copy
a = [[1, 2]]
shallow = copy.copy(a)
deep = copy.deepcopy(a)

Would you like these as a downloadable PDF or want more questions (e.g., multithreading, asyncio, design patterns, etc.)?

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...