Comprehensive, chapter-wise preparation guide covering 200 Python developer interview questions with step-by-step answers.
Q1. What are Python’s key features?
- Interpreted execution eases debugging.
- Dynamic typing infers types at runtime.
- High-level abstractions manage memory and data structures.
- Extensive standard library covers I/O, networking, parsing.
- Multi-paradigm support spans procedural, OOP, functional styles.
- Portability across platforms through multiple interpreters.
- Vibrant ecosystem of packages and community support.
Q2. How do CPython, PyPy, and Jython differ?
- CPython compiles to bytecode executed by C-based VM.
- PyPy includes a JIT for faster execution of many workloads.
- Jython runs on JVM for Java interoperability.
- IronPython targets .NET CLR.
- Choose interpreter based on interoperability and performance needs.
Q3. Explain Python’s execution model from source to runtime.
- Parser converts source to abstract syntax tree (AST).
- Compiler transforms AST to bytecode (
.pyc). - Python Virtual Machine executes bytecode.
- Compiled bytecode cached in
__pycache__for reuse.
Q4. What are PEPs and why are they important?
- Python Enhancement Proposals document language changes.
- Categories include Standard, Informational, and Process PEPs.
- Key examples: PEP 8 (style guide), PEP 20 (Zen of Python), PEP 3333 (WSGI).
- Workflow involves drafting, discussion, and acceptance or rejection.
Q5. Describe Python namespaces and scope resolution.
- Namespaces map identifiers to objects (e.g., module dictionaries).
- Scope lookup follows LEGB: Local, Enclosing, Global, Built-in.
locals()andglobals()expose current scope mappings.- Namespace packages and modules maintain separate
__dict__mappings.
Q6. How does pass differ from continue and break?
passis a no-op placeholder.continueskips to next loop iteration.breakexits the nearest loop.- Use
passin stubs,continuefor filtering,breakfor termination.
Q7. How does Python handle indentation?
- Significant indentation defines code blocks.
- Mixing tabs and spaces raises
TabError. - PEP 8 recommends four spaces per indent level.
- Formatters (black, autopep8) enforce consistent indentation.
Q8. Distinguish expressions, statements, and declarations.
- Expressions return values (e.g.,
2 + 3). - Statements perform actions (e.g.,
if,for). - Python uses assignments as statements rather than declarations.
- Dynamic typing eliminates explicit declarations.
Q9. Explain name binding and rebinding.
- Binding associates identifiers with objects.
- Rebinding assigns new objects to existing names.
- Mutation changes object state without rebinding.
- Immutable types require rebinding to represent new values.
Q10. What is duck typing?
- Behavior determined by available methods and attributes.
- Example: any object with
__iter__acts as iterable. - Encourages flexible polymorphism.
- May raise runtime errors if expected interface missing.
Q11. Describe truthiness rules.
- Falsy values include
False,None, zeros, and empty containers. bool(obj)calls__bool__, falling back to__len__.- Truthiness drives conditionals and loops.
- Custom classes can define boolean evaluation behavior.
Q12. What is short-circuit evaluation?
- Logical operators stop once outcome determined.
A and BreturnsBifAtruthy, elseA.A or BreturnsAif truthy, elseB.- Enables guard expressions to prevent errors.
Q13. What is the difference between == and is?
==invokes__eq__for value equality.ischecks object identity (same memory).- Interning may reuse objects but should not be relied upon.
- Use
isfor singletons likeNone.
Q14. Explain chained comparisons.
a < b < cevaluates once per operand.- Equivalent to
a < b and b < c. - Supports mixed operators (
a < b == c). - Improves clarity when checking ranges.
Q15. How do import statements work?
- Search built-ins, then
sys.modules, then paths insys.path. - Imports execute module top-level code once.
- Cache prevents re-execution on subsequent import.
- Avoid
from module import *for clarity.
Q16. What is the difference between a module and a package?
- Module is a single
.pyfile. - Package is a directory with
__init__.py(or namespace package). - Subpackages nest directories.
- Namespace packages can span multiple locations.
Q17. How do docstrings work?
- Triple-quoted string after definition stored in
__doc__. - Applies to modules, classes, and functions.
- Access via
help()and documentation tools. - Follow PEP 257 formatting.
Q18. What is the purpose of if __name__ == "__main__":?
- Distinguishes script execution from module import.
- Code under guard runs only when executed directly.
- Enables CLI entry points without import side effects.
- Supports module reuse.
Q19. How are command-line arguments handled?
sys.argvlists script name and arguments.argparseprovides structured parsing and validation.- Libraries like
clickandtyperadd higher-level ergonomics. - Document CLI usage and defaults.
Q20. How does Python manage memory?
- Reference counting frees objects with zero references.
- Cyclic garbage collector handles reference cycles.
pymallocmanages small object allocation.- Manual GC control via
gcmodule rarely needed.
Q21. How are lists implemented and when to use them?
- Lists are dynamic arrays supporting amortized O(1) append.
- Ideal for ordered, mutable collections.
- Provide slicing, comprehension, and in-place mutations.
- Prefer sets or dicts for heavy membership checks.
Q22. Explain tuple characteristics and uses.
- Tuples are immutable sequences.
- Hashable when containing hashable elements, suitable as dict keys.
- Support packing/unpacking semantics.
- Namedtuples or dataclasses improve readability when fields named.
Q23. Distinguish list comprehension versus generator expression.
- List comprehensions eagerly build lists in memory.
- Generator expressions yield items lazily with constant memory.
- Syntax differs by brackets (
[]vs()). - Choose based on need for a list versus streaming consumption.
Q24. How do sets work internally?
- Sets use hash tables to store unique elements.
- Provide average O(1) membership tests.
- Support set algebra operations (
|,&,-). frozensetsupplies an immutable, hashable counterpart.
Q25. What are dictionaries and why are they powerful?
- Hash-table-based mappings from keys to values.
- Preserve insertion order in CPython 3.7+.
- Methods include
get,setdefault,update,items. - Fit configuration, caching, and object-like storage scenarios.
Q26. Explain dictionary view objects.
keys(),values(), anditems()return dynamic views.- Views reflect live changes in dictionaries.
- Set operations supported on keys and items.
- Views avoid copying large collections.
Q27. When to use collections.defaultdict vs dict.setdefault?
defaultdictauto-creates default values for missing keys.setdefaultinserts defaults manually per access.defaultdictcleaner for frequent default insertions.- Use
setdefaultfor finer control with varying defaults.
Q28. Describe collections.Counter.
- Specialized dict mapping elements to counts.
- Provides
most_common, arithmetic operations, andelements. - Efficient for frequency analysis.
- Combine counters via addition/subtraction.
Q29. How do slicing rules work for sequences?
seq[start:stop:step]returns subsequences.- Start inclusive, stop exclusive.
- Defaults: start=0, stop=len, step=1.
- Negative indices reference from end; negative step reverses.
Q30. Explain shallow vs deep copies.
- Shallow copies recreate container but reference same items.
- Deep copies recursively duplicate nested objects.
- Use
copy.copyandcopy.deepcopy. - Override
__copy__when custom copy behavior required.
Q31. What is a memoryview and when useful?
- Exposes buffer interface without duplicating data.
- Works with bytes-like objects for zero-copy slices.
- Use for IO-heavy operations to reduce allocations.
- Supports casting formats and slicing.
Q32. How do bytearray and bytes differ?
bytesimmutable;bytearraymutable.- Both represent sequences of integers (0–255).
bytearrayallows in-place modifications.- Convert via
.encode()/.decode().
Q33. How are strings stored and manipulated?
- Strings are immutable Unicode sequences.
- CPython uses flexible internal representation (1/2/4 bytes per char).
- Methods include
strip,split,join,format,casefold. - Encode/decode for conversions to bytes.
Q34. Explain join vs concatenation.
''.join(iterable)efficiently concatenates multiple strings.- Repeated
+or+=creates intermediate objects. - Prefer
StringIOfor incremental building when necessary.
Q35. Discuss in operator semantics.
- Calls
__contains__if defined; otherwise iterates. - For dicts, checks keys.
- Strings use substring search.
- Performance depends on underlying data structure.
Q36. How do sorted and .sort() differ?
sorted(iterable)returns new list.list.sort()sorts in place and returnsNone.- Both employ stable Timsort with
keyandreverseoptions. - Avoid assigning result of
.sort()to a variable.
Q37. Explain bisect module usage.
- Provides binary search helpers for sorted lists.
bisect_leftandbisect_rightfind insertion points.insortinserts while preserving order.- Maintains sorted lists without re-sorting.
Q38. Describe array module vs list.
- Arrays store uniform numeric data with less memory.
- Use type codes (
'i','f') for element types. - Faster numeric operations than lists of Python objects.
- Useful when NumPy unavailable.
Q39. When to use deque?
- Double-ended queue with O(1) append/pop on both ends.
- Methods include
appendleft,popleft,rotate. - Excellent for BFS and sliding windows.
- Optional
maxlencreates fixed-size buffers.
Q40. What is heapq good for?
- Implements priority queue as min-heap.
- Operations include
heappush,heappop,heapreplace. nlargestandnsmallestextract top elements efficiently.- Custom ordering via tuples or decorated values.
Q41. How do default arguments work and what pitfalls exist?
- Defaults evaluated once at function definition.
- Mutable defaults persist between calls causing bugs.
- Use sentinel (e.g.,
None) and assign inside function. - Document behavior of optional parameters.
Q42. Explain positional-only and keyword-only parameters.
- Use
/to mark positional-only parameters. - Use
*to mark keyword-only parameters. - Helps enforce API usage and clarity.
- Example:
def func(a, /, b, *, c): ....
Q43. How does *args and **kwargs work?
*argscaptures extra positional arguments as tuple.**kwargscaptures keyword arguments as dict.- Expand sequences with
*and mappings with**. - Validate arguments to avoid silent errors.
Q44. What are function annotations used for?
- Provide metadata in
__annotations__(often type hints). - Not enforced at runtime.
- Works with tools like mypy and IDEs.
- Can support documentation or custom processing.
Q45. How to create higher-order functions?
- Functions accept or return other functions.
- Utilize closures to capture state.
- Example factory pattern multiplies input by constant.
- Enables flexible composition and callbacks.
Q46. Explain closures.
- Inner functions retain access to enclosing scope variables.
- Stored in function’s
__closure__. - Use
nonlocalto modify captured variables. - Implement factories and stateful behaviors.
Q47. When to use lambda?
- Concise anonymous functions for simple expressions.
- Avoid complex logic; prefer
deffor readability. - Common in callbacks, sorting keys.
- Lambdas return expression results automatically.
Q48. How does map, filter, reduce compare to comprehensions?
mapapplies transformation lazily.filterselects items based on predicate.reducefolds iterable with binary function.- Comprehensions often clearer but functions integrate with existing callables.
Q49. Explain partial application with functools.partial.
- Pre-binds arguments to functions, returning new callable.
- Simplifies repeated function calls with fixed parameters.
- Maintains original metadata via
partial.func. - Cleaner alternative to small lambdas.
Q50. What is functools.lru_cache?
- Decorator caches function results keyed by arguments.
- Controls cache size with
maxsize. typed=Truedifferentiates arguments by type.- Inspect performance via
.cache_info()and reset with.cache_clear().
Q51. How to implement function decorators?
- Decorator receives function and returns wrapper.
- Use
functools.wrapsto preserve metadata. - Inside wrapper handle pre/post logic then call original.
- Apply via
@decoratorsyntax above function definition.
Q52. Explain decorator order when stacking.
- Decorators apply bottom-up; nearest to function runs first.
@Aabove@BmeansA(B(func)).- Order affects behavior when decorators interact.
- Document stacking expectations to avoid surprises.
Q53. What is functools.singledispatch?
- Provides generic functions dispatching on first argument type.
- Use
@singledispatchon base implementation. - Register specialized implementations via
.register(Type). singledispatchmethodextends pattern to class methods.
Q54. How do generators differ from iterators?
- Generators defined with
yieldproduce values lazily. - Generators automatically implement iterator protocol.
- Iterators require
__iter__and__next__. - Use generators for large or infinite sequences.
Q55. Explain generator expressions vs generator functions.
- Expressions offer concise inline generators.
- Functions allow complex logic, multiple yields, state.
- Choose expression for simple transformations.
- Prefer function when control flow or readability demands.
Q56. How does yield from work?
- Delegates part of generator to sub-iterator.
- Eliminates manual loops yielding from nested iterables.
- Propagates
send,throw,closecalls. - Simplifies coroutine composition.
Q57. What is the difference between return and yield inside generators?
yieldemits next value and suspends execution.return valueraisesStopIteration(value)with final result.yieldmaintains generator state;returnterminates.- Access return value via
generator.valuein Python 3.3+.
Q58. How do context managers relate to functions?
withstatement ensures setup/teardown around block.contextlib.contextmanagerturns generator into context manager.yieldsplits enter and exit logic.- Guarantees cleanup of resources (files, locks).
Q59. Explain recursion limits and tail recursion.
- Python sets recursion depth limit to prevent overflow.
- No tail-call optimization; tail recursion still consumes stack.
- Convert deep recursion to iterative approach when possible.
- Adjust limit cautiously via
sys.setrecursionlimit.
Q60. How to document functions effectively?
- Use docstrings describing purpose, parameters, returns, exceptions.
- Follow style guides (Google, NumPy, reST).
- Pair with type hints for clarity.
- Keep documentation consistent across codebase.
Q61. How are classes created and what is __init__?
classstatement executes to build class namespace.__init__runs post-instantiation to initialize attributes.__new__controls object creation if overridden.- Python 3 implicitly inherits from
object.
Q62. Explain inheritance in Python.
- Subclasses extend base classes using
class Sub(Base):. - Multiple inheritance supported; follow MRO.
- Use
super()to access parent implementations. - Design mixins for reusable behaviors.
Q63. What is method resolution order (MRO)?
- Determines attribute lookup order in inheritance hierarchy.
- Python uses C3 linearization.
- Inspect via
Class.__mro__orClass.mro(). - Ensures predictable lookup with multiple inheritance.
Q64. How do class and static methods differ?
@classmethodreceives class (cls).@staticmethodreceives no implicit arguments.- Instance methods receive
self. - Use classmethods for alternate constructors or class-level operations.
Q65. Explain properties and descriptors.
propertyconverts methods into managed attributes.- Descriptors implement
__get__,__set__,__delete__. - Data descriptors override instance dictionaries.
- Enable validation, caching, computed attributes.
Q66. What is __slots__?
- Declares fixed attribute set to avoid per-instance
__dict__. - Reduces memory usage and speeds attribute access.
- Syntax:
__slots__ = ('x', 'y'). - Limits dynamic attribute creation; impacts inheritance.
Q67. Explain operator overloading.
- Implement special methods (
__add__,__eq__, etc.) for operators. - Return
NotImplementedwhen operation unsupported. - Ensure behavior remains predictable and consistent.
functools.total_orderingcan derive comparison methods.
Q68. How does __repr__ differ from __str__?
__repr__yields unambiguous developer-facing representation.__str__produces user-friendly string.repr(obj)calls__repr__;str(obj)falls back to__repr__.- Provide informative diagnostics in
__repr__.
Q69. Describe dynamic attribute access.
__getattr__called for missing attributes.__getattribute__intercepts all accesses; use carefully.__setattr__and__delattr__manage assignment/deletion.- Useful for proxies, lazy loading, and dynamic APIs.
Q70. What are metaclasses?
- Classes of classes controlling class creation.
- Default metaclass
typecan be customized by overriding__new__. - Declare via
class Foo(metaclass=Meta):. - Apply to enforce interfaces or auto-register subclasses.
Q71. How does multiple inheritance using mixins work?
- Mixins provide focused functionality combined with other bases.
- Conventionally named
SomethingMixin. - Ensure mixin methods call
super()to cooperate. - Document dependencies and expected attributes.
Q72. Explain abstract base classes (ABCs).
- Defined with
abcmodule and@abstractmethod. - Prevent instantiation until abstract methods implemented.
- Support virtual subclassing via
register. - Enforce interface contracts.
Q73. How does dataclasses simplify class creation?
@dataclassauto-generates init, repr, eq, etc.- Fields configured via
field(defaults, metadata). - Supports default factories and post-init hooks.
- Works with type hints to document structure.
Q74. When to use __post_init__?
- Executes after dataclass-generated
__init__. - Ideal for validation or derived attribute assignment.
- Pair with
init=Falsefields to set computed values.
Q75. Compare namedtuple vs dataclass.
namedtuplelightweight, immutable, tuple-based.dataclassmutable by default with richer feature set.- Choose based on mutability and method needs.
typing.NamedTupleadds type hints using class syntax.
Q76. Explain method overriding and super().
- Subclass redefines method from base class.
super()invokes next method in MRO chain.- Use especially in
__init__for cooperative initialization. - Zero-argument
super()preferred in modern Python.
Q77. How to implement singleton pattern?
- Override
__new__to return existing instance. - Alternatively use module-level singletons.
- Ensure thread safety if accessed concurrently.
- Evaluate whether dependency injection is better alternative.
Q78. Explain composition vs inheritance.
- Composition assembles behavior via contained objects (has-a).
- Inheritance extends behavior via parent classes (is-a).
- Favor composition to reduce coupling and increase flexibility.
- Use inheritance when substitutability requirements exist.
Q79. Describe polymorphism in Python.
- Objects with shared interface can be used interchangeably.
- Duck typing allows polymorphism without inheritance.
- ABCs and Protocols formalize interfaces when needed.
- Enables decoupled, modular code design.
Q80. How to serialize custom objects?
- Implement
__getstate__/__setstate__for pickle control. - Convert to dictionaries for JSON serialization.
- Utilize libraries (marshmallow, pydantic) for validation and schemas.
- Never unpickle untrusted data due to security risks.
Q81. How to structure a Python project?
- Adopt
src/or flat layout with clear package boundaries. - Include
pyproject.toml, README, tests, and docs. - Separate application logic from configuration/resources.
- Follow modern packaging best practices.
Q82. Explain __init__.py role.
- Marks directory as package (unless using namespace packages).
- Executes during package import.
- Re-export public API elements for convenience.
- Avoid expensive side effects in package initialization.
Q83. What is a virtual environment?
- Isolated interpreter environment with independent dependencies.
- Create with
python -m venv env. - Activation adjusts PATH to use environment-specific Python.
- Prevents dependency conflicts across projects.
Q84. Compare pip, pipenv, and poetry.
pipinstalls packages using requirements files.pipenvcombines pip and virtualenv with Pipfile/lock.poetrymanages dependencies, lockfiles, and builds in one tool.- Select tool aligning with team workflow.
Q85. How does dependency resolution work?
- Installer computes compatible versions to satisfy requirements.
- Lockfiles capture resolved versions for reproducibility.
- Semantic version specifiers guide upgrade boundaries.
- Regular updates mitigate security risks.
Q86. Describe packaging with pyproject.toml.
- PEP 518/621 define build-system configuration in TOML.
[build-system]specifies backend (setuptools, poetry).[project]holds metadata like name, version, dependencies.- Replaces
setup.pyfor many modern packages.
Q87. How to publish a package to PyPI?
- Prepare metadata, README, and license.
- Build distribution via
python -m build. - Upload using
twine upload dist/*. - Test on TestPyPI before full release.
Q88. What are entry points?
- Configure console scripts in packaging metadata.
- Map command names to module callables.
- Powers plugin systems (e.g., pytest).
- Example:
[project.scripts] cli = pkg.module:main.
Q89. How does module caching work?
sys.modulesstores loaded modules.- Re-importing returns cached module object.
importlib.reloadre-executes module code when needed.- Understand for plugin management and hot reloading.
Q90. When to use relative vs absolute imports?
- Absolute imports (
from package import module) preferred for clarity. - Relative imports (
from .submodule import name) reduce repetition inside packages. - Avoid deep relative paths to maintain readability.
- Stay consistent within project.
Q91. Explain importlib utilities.
import_moduledynamically imports modules by string name.importlib.resourcesaccesses package data files.importlib.metadataretrieves installed package metadata.- Useful for plugin systems and runtime configuration.
Q92. How to manage configuration?
- Use environment variables, config files, or dedicated modules.
- Libraries such as
configparser,pydantic,dynaconfprovide structure. - Separate config per environment.
- Store secrets securely and avoid hardcoding.
Q93. How does logging configuration work?
loggingmodule manages hierarchical loggers.- Configure via
basicConfig, dictConfig, orfileConfig. - Handlers, formatters, and filters control output.
- Prefer logging over
printfor production diagnostics.
Q94. Explain environment management across OSes.
python -m venvworks cross-platform.- Activation scripts differ on Windows vs Unix.
- For Python versions, use
pyenv(Unix) or installs via official sources on Windows. - Document setup steps for contributors.
Q95. What is site-packages?
- Directory containing installed third-party packages.
- Virtual environments maintain isolated site-packages directories.
- Inspect paths via
site.getsitepackages(). pip install --targetinstalls to custom locations.
Q96. How to handle namespace packages?
- Omit
__init__.pyto allow package spanning multiple directories. - Native namespace packages require PEP 420 support.
- Useful for large projects split across repos.
- Manage to avoid import collisions.
Q97. Explain __all__ usage.
- Defines public names exported by
from module import *. - Controls module API surface.
- Documentation tools may respect
__all__. - Optional but helpful for clarity.
Q98. How to create reusable CLI tools?
- Encapsulate entry logic in
main()function. - Use
argparse,click, ortyperfor argument parsing. - Provide console script entry points in metadata.
- Include
--helpmessages and usage examples.
Q99. How to version a package?
- Follow semantic versioning (MAJOR.MINOR.PATCH).
- Store version in module (
__version__) or metadata. - Automate bumps with
setuptools_scmorbumpversion. - Maintain changelog synchronized with releases.
Q100. What is a wheel file?
- Binary distribution format with
.whlextension. - Enables fast installs without build step.
- Pure Python wheels universal; binary wheels platform specific.
- Generate via
python -m build.
Q101. How do decorators work under the hood?
- Function object passed to decorator at definition time.
- Decorator returns wrapper replacing original function.
- Equivalent to assignment
func = decorator(func). - Parameterized decorators return decorator factory.
Q102. Explain descriptor protocol.
- Objects implementing
__get__,__set__,__delete__control attribute access. - Data descriptors define both
__get__and__set__. - Non-data descriptors (like functions) only implement
__get__. - Foundation for properties, methods, and managed attributes.
Q103. What is monkey patching?
- Runtime modification of modules or classes by reassignment.
- Useful in testing or compatibility fixes.
- Risky due to hidden side effects.
- Use
unittest.mock.patchto scope patches safely.
Q104. How does __call__ enable callable objects?
- Defining
__call__makes instances behave like functions. - Supports stateful operations with function interface.
- Combine with
functools.update_wrapperto mimic function metadata. - Useful in strategy patterns and configurables.
Q105. Explain context manager protocol.
__enter__executes at block start, returning value.__exit__handles cleanup and receives exception info.- Returning True from
__exit__suppresses exception propagation. - Manage resources reliably with
withstatements.
Q106. What is contextlib.ExitStack?
- Manages dynamic stacks of context managers.
- Allows programmatic entering of contexts.
- Guarantees LIFO cleanup even with variable resources.
- Supports registering arbitrary callbacks via
callback().
Q107. How do slots interact with inheritance?
- Subclasses must define their own
__slots__including inherited names. - Without
__slots__, subclass gains__dict__. - Multiple inheritance requires careful slot configuration.
- Include
'__weakref__'if instances need weak references.
Q108. Explain interplay of method decorators.
@propertyapplies only to instance methods.@classmethodand@staticmethodcannot combine with@property.- For class-level properties, use metaclass or descriptors.
- Decorator order affects resulting descriptor type.
Q109. What is the __prepare__ method in metaclasses?
- Called before class body execution to provide custom namespace.
- Returns mapping used for class attributes (e.g., OrderedDict).
- Useful for DSLs or tracking declaration order.
- Allows validation during class creation.
Q110. How does enum module work?
Enumdefines symbolic names bound to constant values.- Members are unique and comparable by identity.
auto()assigns incremental values automatically.IntEnumandFlagprovide numeric interoperability and bit flags.
Q111. Explain typing module basics.
- Type hints annotate variables and functions.
- Use
List,Dict,Optional,Union,Callable. - Python 3.9+ supports builtin generic types (
list[int]). - Type hints aid static analysis, documentation, IDE assistance.
Q112. How do Protocols support structural typing?
typing.Protocoldefines required methods/attributes.- Classes implementing structure implicitly satisfy protocol.
- Enables duck typing with static type checking.
- Use
runtime_checkablefor runtime isinstance checks.
Q113. Explain typing.NewType.
- Creates distinct type alias for static checking.
UserId = NewType("UserId", int)differentiates from plain int.- Runtime value equals underlying type.
- Enhances type safety without runtime cost.
Q114. What is covariance and contravariance?
- Covariant types allow substitution with subtypes.
- Contravariant types allow substitution with supertypes.
- Python generics default to invariance unless declared.
- Use
TypeVar('T_co', covariant=True)for covariance.
Q115. How does typing.Any differ from object?
Anydisables static type checking for value.objectenforces explicit casting or attribute checks.- Overuse of
Anyreduces type safety. - Reserve
Anyfor truly dynamic interfaces.
Q116. Explain typing.TypedDict.
- Defines dict-like structures with fixed key types.
- Supports optional keys and total/partial modes.
- Ideal for JSON payloads and configuration schemas.
- Works with type checkers to validate dict shape.
Q117. What is pattern matching (PEP 634)?
match/caseenable structural pattern matching.- Supports literals, sequences, mappings, class patterns.
- Guard clauses add conditional filters.
case _acts as default fallback.
Q118. Explain dataclasses.field options.
defaultanddefault_factoryspecify default values.- Flags like
init,repr,compare,hashcustomize behavior. metadatastores arbitrary information.- Use
init=Falsefor computed fields set in__post_init__.
Q119. How does functools.cache differ from lru_cache?
cacheis unlimited-size variant introduced in Python 3.9.- Equivalent to
lru_cache(maxsize=None). - Simplified decorator when eviction unnecessary.
- Manage unbounded growth carefully.
Q120. What is weakref module for?
- Maintains references without preventing garbage collection.
- Supports caches, observer patterns, and avoidance of cycles.
WeakKeyDictionaryandWeakValueDictionaryauto-remove collected objects.- Objects need
__weakref__support to be weakly referencable.
Q121. Describe the Global Interpreter Lock (GIL).
- Mutex in CPython allowing one thread to execute bytecode at a time.
- Simplifies memory management but limits CPU-bound threading.
- I/O operations release GIL, enabling concurrency for blocking IO.
- Alternatives include multiprocessing, asyncio, or C extensions.
Q122. When to use threading module?
- Best for I/O-bound tasks (network, disk).
- Provides
Thread,Lock,Event,Condition,Semaphore. - Protect shared state with synchronization primitives.
- GIL restricts CPU-bound scaling.
Q123. How does queue.Queue help concurrency?
- Thread-safe FIFO structure for producer-consumer patterns.
put,get,task_done,joinmanage coordination.- Supports blocking operations with timeouts.
- Variants include
LifoQueueandPriorityQueue.
Q124. Compare multiprocessing to threading.
multiprocessinglaunches separate processes bypassing GIL.- Ideal for CPU-intensive workloads.
- Overhead includes inter-process communication and process startup.
- Provides
Process,Pool,Manager.
Q125. What is concurrent.futures?
- High-level API for parallel execution.
ThreadPoolExecutorandProcessPoolExecutor.- Futures represent asynchronous results with callbacks.
- Methods:
submit,map,as_completed.
Q126. How does asyncio event loop function?
- Manages scheduling of coroutines and callbacks.
asyncio.runstarts and manages event loop lifecycle.- Coroutines yield control via
await, enabling cooperative multitasking. - Single-threaded but handles massive concurrent I/O.
Q127. Explain coroutines and async/await.
async defdefines coroutines returning awaitable objects.awaitpauses coroutine until awaited task completes.- Coroutines integrate with event loop for non-blocking operations.
- Compose with tasks, futures, and gather patterns.
Q128. How to create asynchronous context managers?
- Implement
__aenter__and__aexit__. - Use
async withfor asynchronous resource management. contextlib.asynccontextmanagersimplifies generator-based contexts.- Ensure proper cleanup of async resources.
Q129. When to use asyncio.TaskGroup?
- Python 3.11 structured concurrency primitive.
- Groups related tasks with automatic cancellation on failure.
- Ensures deterministic cleanup of child tasks.
- Use
async with TaskGroup() as tg:to spawn tasks.
Q130. How does async exception propagation work?
- Exceptions raised inside coroutine surface when awaited.
- Background tasks log unhandled exceptions; inspect via
task.exception(). - Use
asyncio.gatherwithreturn_exceptions=Trueto collect failures. - Structured concurrency simplifies error handling.
Q131. Explain asyncio.Queue.
- Asynchronous FIFO for coroutine communication.
await queue.put()andawait queue.get()operations.- Supports maxsize,
task_done,join. - Useful in producer-consumer coroutine patterns.
Q132. How to integrate blocking code in async context?
- Offload to thread with
asyncio.to_thread()(Py3.9+). - Alternatively use
loop.run_in_executor. - Prevents blocking event loop.
- For CPU-bound work, consider process pool.
Q133. Explain actor model with multiprocessing.
- Actors encapsulate state and communicate via messages.
- Use queues or pipes for inter-process messaging.
- Avoid shared mutable state.
- Simplifies reasoning about concurrency and failure isolation.
Q134. What is Gevent/eventlet?
- Third-party libraries using greenlets for cooperative multitasking.
- Monkey patch blocking operations for async behavior.
- Suited for network servers requiring large concurrency.
- Not part of standard library; evaluate compatibility implications.
Q135. How to manage concurrency in web frameworks?
- Async frameworks (FastAPI, aiohttp) for I/O scalability.
- Understand server concurrency models (WSGI vs ASGI).
- Offload CPU-heavy tasks to background workers.
- Configure database pools for concurrent access.
Q136. What is asyncio.Lock and when needed?
- Async mutual exclusion primitive.
- Use
async with lock:to guard shared state. - Prevents simultaneous coroutine access to critical sections.
- Avoid unnecessary locking to maintain throughput.
Q137. Explain cancellation in asyncio.
task.cancel()requests cancellation raisingCancelledError.- Coroutines should catch and handle for cleanup.
asyncio.shieldprotects tasks from cancellation.- Task groups propagate cancellation to child tasks.
Q138. How do deadlines and timeouts work?
asyncio.wait_forenforces timeout on awaitables.- Python 3.11
asyncio.timeoutcontext simplifies usage. - Threads use timeouts on blocking calls (e.g.,
queue.get). - Unix-only
signalmodule allows alarm-based timeouts.
Q139. Discuss concurrency pitfalls.
- Race conditions arise from unprotected shared state.
- Deadlocks occur with circular lock acquisition.
- Starvation happens when tasks are perpetually deferred.
- Data corruption results from non-atomic operations.
Q140. When to choose reactive frameworks like RxPY?
- Suitable for event-driven, stream-processing applications.
- Offers composable operators for transformation and filtering.
- Integrates with asyncio for async streams.
- Beware of steep learning curve and complexity.
Q141. How to structure unit tests?
- Use
unittestorpytestframeworks. - Follow Arrange-Act-Assert pattern.
- Keep tests deterministic and isolated.
- Name tests descriptively for readability.
Q142. Why prefer pytest fixtures?
- Provide reusable setup and teardown logic.
- Support scopes (function, module, session).
- Enable parametrization for input variations.
- Simplify dependency injection.
Q143. How does mocking work with unittest.mock?
patchreplaces objects during tests (target where used).Mock/MagicMockauto-create attributes.- Assert behavior with
assert_called_once_with. - Use context managers or decorators to limit patch scope.
Q144. Explain property-based testing.
- Use
hypothesisto generate test cases automatically. - Define invariants rather than specific examples.
- Reveals edge cases beyond manual tests.
- Combine with unit tests for thorough coverage.
Q145. How to test asynchronous code?
- Use
pytest.mark.asyncioor event loop fixtures. - Await coroutines within async tests.
- Mock async functions with
AsyncMock. - Ensure event loop cleanup between tests.
Q146. How do you profile Python code?
cProfileprofiles function call statistics.- Analyze with
pstatsor visualize viasnakeviz. timeitevaluates micro-benchmarks.- Profile realistic workloads to identify bottlenecks.
Q147. Explain debugging with pdb.
- Launch via
python -m pdb script.pyorpdb.set_trace(). - Commands:
n(next),s(step),c(continue),l(list). - Set breakpoints with
break. - Enhanced debuggers (
ipdb,pudb) add usability.
Q148. What are linters and formatters?
- Linters (flake8, pylint) detect style and logical issues.
- Formatters (black, yapf) enforce consistent style automatically.
- Integrate via pre-commit hooks or CI.
- Combine tools to maintain code quality.
Q149. How to enforce type checking?
- Run
mypy,pyright, orpytype. - Configure settings via config files.
- Address warnings incrementally to improve coverage.
- Use
typing.castsparingly for legitimate overrides.
Q150. Explain continuous integration best practices.
- Automate tests, linters, and type checks on commits.
- Use hosted CI (GitHub Actions, GitLab, Jenkins).
- Maintain deterministic environments with lockfiles.
- Fail fast and provide actionable feedback.
Q151. How to test CLI tools?
- Invoke via
subprocess.runor CLI testing helpers. - Mock environment variables and file system as needed.
- Capture stdout/stderr with pytest’s
capsys. - Validate exit codes and side effects.
Q152. What is mutation testing?
- Intentionally modify code (mutants) to ensure tests detect changes.
- Tools like
mutmutorcosmic-rayautomate process. - Measures robustness of test suite.
- Resource-intensive but uncovers weak tests.
Q153. How to debug memory leaks?
- Use
tracemallocto track allocations. - Inspect object graphs with
objgraph. - Identify reference cycles and caches.
- Break cycles or use weak references to resolve leaks.
Q154. Explain coverage analysis.
coverage.pymeasures executed lines and branches.- Integrate with pytest via
pytest --cov. - Aim for meaningful coverage, not just high percentages.
- Review reports for critical untested paths.
Q155. How to test database interactions?
- Use fixtures to prepare test databases.
- Apply transactions with rollback per test.
- Mock ORM layers when unit testing logic.
- Separate integration tests for full stack validation.
Q156. What is regression testing?
- Ensures new changes do not reintroduce past bugs.
- Maintain regression suite containing previous failures.
- Automate execution to catch regressions early.
- Pair with bug tracking to document coverage.
Q157. How to handle flaky tests?
- Diagnose underlying flakiness (timing, dependencies).
- Stabilize with deterministic setup or isolation.
- Use retries sparingly as temporary mitigation.
- Monitor CI to ensure flakiness resolved.
Q158. Explain test-driven development (TDD).
- Write failing test (red).
- Implement minimal code to pass (green).
- Refactor while keeping tests passing.
- Encourages design clarity and regression safety.
Q159. How to organize test directories?
- Place tests in dedicated
tests/directory. - Mirror application structure for clarity.
- Use
conftest.pyfor shared fixtures. - Mark integration tests for selective runs.
Q160. How to document debugging sessions?
- Record steps, hypotheses, and commands executed.
- Store notes in issue tracker or log.
- Share findings for team knowledge.
- Helps future troubleshooting.
Q161. How to work with files safely?
- Use
with open(path, mode) as fto ensure closure. - Specify encoding (e.g.,
utf-8). - Prefer
pathlibfor cross-platform paths. - Stream large files to avoid memory pressure.
Q162. What is pathlib advantage?
- Object-oriented path manipulations.
- Methods like
.read_text(),.iterdir(),.resolve(). - Interoperable with standard library using
str(path). - Simplifies cross-platform path operations.
Q163. How to perform JSON serialization?
- Use
json.dump/loadfor files andjson.dumps/loadsfor strings. - Provide custom encoders for non-standard types.
- Set
ensure_ascii=Falseandindentfor readability. - Validate data before serialization.
Q164. Explain CSV handling best practices.
- Use
csvmodule with explicit dialects. - Iterate row-by-row for large files.
- Consider
pandasfor complex transformations. - Validate and convert data types explicitly.
Q165. How to connect to databases?
- Use DB-API compliant drivers (
sqlite3,psycopg2). - Manage connections with context managers or pools.
- Parameterize queries to prevent SQL injection.
- Consider ORMs for abstraction layers.
Q166. What is SQLAlchemy?
- Comprehensive ORM and SQL toolkit.
- Declarative models map tables to classes.
- Sessions handle transactions and unit-of-work patterns.
- Alembic manages migrations.
Q167. How to consume REST APIs?
- Use
requestswith timeouts and error handling. - Manage authentication via headers or sessions.
- Parse JSON responses and validate schema.
- For async, use
httpxoraiohttp.
Q168. Explain streaming large downloads.
- Enable streaming with
requests.get(..., stream=True). - Iterate using
iter_contentto process chunks. - Write to disk incrementally to save memory.
- Handle interruptions with resume logic if necessary.
Q169. How to perform web scraping responsibly?
- Respect
robots.txtand site terms. - Use
BeautifulSoup,lxmlfor parsing. - Manage rate limits and caching.
- Handle dynamic content with headless browsers (Selenium, Playwright).
Q170. How to parse XML?
xml.etree.ElementTreehandles simple parsing.lxmloffers XPath and better performance.- Mitigate vulnerabilities (XXE) by disabling external entities.
- Validate against schema when available.
Q171. Explain working with configuration formats (YAML, TOML).
- YAML via
PyYAML, TOML viatomllib(Py3.11+) ortomli. - Be cautious of YAML features that execute code.
- Document schema and defaults.
- Validate configuration before use.
Q172. How to use sqlite3 module?
- Connect with
sqlite3.connect('file.db')or:memory:. - Execute parameterized queries with placeholders.
- Manage transactions explicitly (
commit,rollback). - Enable foreign keys via
PRAGMA foreign_keys = ON.
Q173. What is subprocess module used for?
- Spawn and manage external processes.
- Use
subprocess.runwith lists to avoid shell injection. - Capture output using
capture_output=True. - Handle errors with
check=True.
Q174. How to handle time zones?
- Use timezone-aware
datetimeobjects. zoneinfo(Py3.9+) provides IANA time zone support.- Store times in UTC; convert at boundaries.
- For older versions, use
pytz.
Q175. Explain scheduling tasks.
- Standard
schedfor basic scheduling. - Production use
APScheduler, Celery beat, or cron. - Ensure job idempotency and logging.
- Monitor for missed or failed executions.
Q176. How to handle binary protocols?
- Use
structto pack and unpack binary data. - Specify endianness with format characters.
- For complex protocols, consider libraries like
construct. - Validate payload sizes and integrity.
Q177. Explain caching strategies.
- In-memory caches using dict or LRU.
- Distributed caches (Redis, Memcached) for multi-process scenarios.
- Establish invalidation policies (TTL, explicit purge).
- Consider consistency and staleness impacts.
Q178. How to work with message queues?
- Use libraries (
kombu,pika,celery). - Understand delivery semantics (at-most-once, at-least-once).
- Serialize messages with JSON, Protobuf, or Avro.
- Implement retry and dead-letter handling.
Q179. Explain file locking.
- Unix uses
fcntl; Windows usesmsvcrt. portalockeroffers cross-platform abstraction.- Acquire locks using context managers to ensure release.
- Choose advisory vs mandatory locking per requirement.
Q180. How to handle large data processing?
- Process in streams or chunks to limit memory usage.
- Parallelize with multiprocessing or distributed frameworks (Dask, Spark).
- Profile IO and CPU to balance resources.
- Optimize algorithms before scaling hardware.
Q181. How to design modular systems in Python?
- Apply Single Responsibility Principle for cohesive modules.
- Define interfaces via ABCs or Protocols.
- Use dependency injection for testability.
- Document boundaries and contracts.
Q182. What is Clean Architecture in Python?
- Layers: Entities, Use Cases, Interface Adapters, Frameworks.
- Inner layers independent from outer layers.
- Implement via packages representing each layer.
- Use adapters to interact with external systems.
Q183. How to apply SOLID principles?
- Single Responsibility ensures focused classes.
- Open/Closed encourages extension without modification.
- Liskov Substitution maintains substitutability.
- Interface Segregation and Dependency Inversion promote decoupling.
Q184. Explain microservices vs monolith decisions.
- Monoliths simpler initially; microservices aid team scaling.
- Evaluate deployment complexity and data consistency needs.
- Python supports both with frameworks (Flask, FastAPI, Django).
- Plan service communication (REST, gRPC) and observability.
Q185. How to design RESTful APIs in Python?
- Use frameworks (FastAPI, Flask, Django REST Framework).
- Model endpoints around resources and HTTP verbs.
- Validate input via pydantic or serializers.
- Provide pagination, error handling, and versioning.
Q186. What is asynchronous web architecture?
- ASGI servers (uvicorn, hypercorn) execute async views.
- Async frameworks leverage event loop for concurrency.
- Offload long-running work to background tasks.
- Contrast with WSGI’s synchronous model.
Q187. How to optimize performance?
- Profile first to locate hotspots.
- Use appropriate data structures and algorithms.
- Apply caching/memoization.
- Employ C extensions or vectorized libraries when necessary.
Q188. When to use Cython or CPython extensions?
- Suitable for CPU-bound sections needing C-like speed.
- Cython compiles annotated Python-like code to C.
ctypesandcffiinterface with existing C libraries.- Balance performance gains against build complexity.
Q189. How to handle configuration secrets securely?
- Store secrets outside source control.
- Use environment variables or secret managers (Vault, AWS Secrets Manager).
- Encrypt at rest and restrict access.
- Rotate credentials regularly.
Q190. What is observability stack in Python apps?
- Metrics (Prometheus), logs (JSON/structured), traces (OpenTelemetry).
- Instrument code for distributed tracing.
- Provide health and readiness endpoints.
- Correlate logs with request IDs.
Q191. Explain graceful shutdown.
- Handle termination signals (SIGTERM) for cleanup.
- For asyncio, cancel tasks and close loop.
- Ensure resources (files, DB connections) close properly.
- Implement idempotent cleanup handlers.
Q192. How to handle configuration for multiple environments?
- Layer configs (base + environment overrides).
- Keep secrets separate from general config.
- Document environment variables and defaults.
- Validate configuration during startup.
Q193. What is feature flagging?
- Toggle features at runtime via configuration.
- Support gradual rollouts and A/B testing.
- Implement with config files or services (LaunchDarkly).
- Remove stale flags to reduce complexity.
Q194. How to integrate CI/CD pipelines?
- Automate build, test, lint, and deployment.
- Use Infrastructure as Code tools to manage environments.
- Adopt deployment strategies (blue/green, canary).
- Monitor post-deployment metrics for regressions.
Q195. Explain containerizing Python apps.
- Write
Dockerfileusing official Python base image. - Install dependencies via
requirements.txtor poetry export. - Use multi-stage builds for smaller images.
- Manage configuration through environment variables.
Q196. How to ensure thread-safety in web apps?
- Avoid shared mutable global state.
- Configure WSGI/ASGI server workers and threads appropriately.
- Use thread-safe connection pools.
- Leverage external caches or databases for shared state.
Q197. What is domain-driven design (DDD) in Python?
- Focus on domain model with ubiquitous language.
- Entities, value objects, aggregates structure domain logic.
- Repositories abstract persistence.
- Combine with dataclasses and type hints for clarity.
Q198. How to manage migrations?
- Use Alembic or Django migrations for schema changes.
- Version migrations and run in CI.
- Handle data migrations carefully with scripts or management commands.
- Prepare rollback plans for failures.
Q199. How to implement background processing?
- Use task queues (Celery, RQ, Dramatiq).
- Run workers separate from web servers.
- Manage retries, backoff, and idempotency.
- Monitor queues and task health.
Q200. What are best practices for code reviews?
- Prioritize correctness, readability, maintainability.
- Use review checklists (tests, docs, security).
- Provide specific, constructive feedback.
- Encourage small PRs and automate quality checks.
- Review chapters aligned with target job requirements.
- Implement practice projects and exercises for reinforcement.
- Rehearse explanations aloud to build confidence.
- Pair study with mock interviews or timed practice sessions.