Type hints, duck typing, EAFP/LBYL, monkey patching, introspection, __slots__, hashability, closures, and descriptors.
Question 1: What are type hints?
Ans
Type hints annotate expected types to improve readability, IDE support, static analysis, and documentation. Python does not normally enforce them at runtime by itself.
Example
python
def add(a: int, b: int) -> int:
return a + b
Important Point
Tools such as mypy or pyright can analyze annotations before runtime.
Question 2: What is duck typing?
Ans
Duck typing means code focuses on whether an object supports the required operations rather than requiring a specific nominal type.
Example
python
def save(writer):
writer.write("hello")
Important Point
The phrase comes from behavior: if an object provides the needed interface, the code can use it.
Question 3: What is EAFP?
Ans
EAFP means 'Easier to Ask Forgiveness than Permission'. Python code often performs an operation and catches a specific exception rather than checking every possible condition first.
Example
python
try:
value = data["name"]
except KeyError:
value = "Unknown"
Important Point
Use EAFP when exceptions represent expected control flow; do not catch broad exceptions.
Question 4: What is LBYL?
Ans
LBYL means 'Look Before You Leap'. Code checks a condition before performing an operation that might fail.
Example
python
if "name" in data:
value = data["name"]
Important Point
LBYL can be useful when the check is cheap and avoids an expensive or disruptive failure, but the condition can still change between check and use in concurrent code.
Question 5: What is monkey patching?
Ans
Monkey patching changes or replaces attributes of modules or classes at runtime.
It can be useful in controlled tests, but uncontrolled runtime patching can make systems difficult to reason about.
Question 6: What is introspection?
Ans
Introspection means examining objects, types, attributes, signatures, or other runtime information from within a program.
Example
python
class User:
pass
u = User()
print(type(u))
print(hasattr(u, "name"))
Important Point
Reflection and introspection are powerful, but explicit interfaces are usually easier to maintain.
Question 7: What is `__slots__`?
Ans
__slots__ can restrict which instance attributes are stored and may reduce per-instance memory usage by avoiding a normal instance dictionary in suitable classes.
Example
python
class Point:
__slots__ = ("x", "y")
def __init__(self, x, y):
self.x, self.y = x, y
Important Point
Slots change class behavior and can affect inheritance, weak references, and dynamic attributes; benchmark before using them for optimization.
Question 8: What is hashability?
Ans
A hashable object has a hash value that remains stable during its lifetime and can be compared for equality. Hashable objects can be dictionary keys and set elements.
Mutable objects whose equality/hash can change should not be used as hash keys.
Question 9: What is a closure?
Ans
A closure is a function that retains access to variables from its enclosing lexical scope even after the outer function has returned.
Example
python
def multiplier(n):
def multiply(x):
return x * n
return multiply
double = multiplier(2)
print(double(5))
Important Point
Closures capture bindings; use `nonlocal` when the nested function needs to reassign an enclosing variable.
Question 10: What is late binding in closures?
Ans
Nested functions created in a loop commonly look up captured variables when called, not when the function is created. This can make every callback observe the final loop value.
Example
python
funcs = [lambda: i for i in range(3)]
print([f() for f in funcs]) # [2, 2, 2]
Important Point
Capture the current value explicitly, for example with a default argument such as `lambda i=i: i`.
Question 11: What is a descriptor?
Ans
A descriptor is an object implementing methods such as __get__, __set__, or __delete__, allowing it to control attribute access. Properties, methods, and many framework features rely on descriptor behavior.
Example
python
class Positive:
def __set_name__(self, owner, name): self.name = name
def __get__(self, obj, owner=None): return obj.__dict__[self.name]
def __set__(self, obj, value):
if value <= 0: raise ValueError("must be positive")
obj.__dict__[self.name] = value
Important Point
Descriptors are an advanced mechanism; understand properties and class attribute lookup before using custom descriptors.
Question 12: What is an abstract base class?
Ans
An abstract base class uses the abc module to define methods that subclasses are expected to implement and can prevent incomplete classes from being instantiated.
Example
python
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self): pass
Python's ordinary method overloading does not select implementations by argument type in the same way as languages such as Java. Multiple-dispatch behavior can be implemented with tools such as functools.singledispatch for dispatch based on the first argument's type.