Skip to content

Portal | Level: L1: Foundations | Topics: Python | Domain: DevOps & Tooling

Python — Trivia & Knowledge Compendium

~800+ Q&A pairs covering everything from Guido's Christmas vacation project to CPython's small integer cache. Compiled from local study materials, interview prep banks, certification resources, and web research.

Last updated: 2026-03-26


1. Origins, History & Trivia

Q: Why is the language called "Python"?

A: Guido van Rossum named it after "Monty Python's Flying Circus," the British comedy group, not the snake.

Q: When did Guido van Rossum start working on Python?

A: Late December 1989, during Christmas vacation at CWI in Amsterdam. He was looking for a hobby programming project to keep him occupied.

Q: What language was Python's direct predecessor at CWI Amsterdam?

A: ABC — Guido worked on the ABC language at CWI and Python was partly inspired by it, borrowing ideas like indentation-based syntax, high-level data types, and interactive use.

Q: When was Python 0.9.0 first released publicly?

A: February 20, 1991, posted to the alt.sources Usenet newsgroup.

Q: What features did Python 0.9.0 already include?

A: Classes with inheritance, exception handling, functions, the core data types (list, dict, str), and a module system. It was remarkably complete for a first public release.

Q: When was Python 1.0 released?

A: January 1994. It added lambda, map, filter, and reduce — functional programming features inspired by Lisp.

Q: When was Python 2.0 released and what did it add?

A: October 16, 2000. It introduced list comprehensions (PEP 202) and a cycle-detecting garbage collector.

Q: When was Python 3.0 released?

A: December 3, 2008. It was intentionally backward-incompatible to fix fundamental design issues like the print statement vs function, integer division, and Unicode handling.

Q: What were the main breaking changes in Python 3.0?

A: print became a function, / does true division by default, all strings are Unicode, range() returns an iterator, dict.keys()/values()/items() return views, and many functions return iterators instead of lists.

Q: When did Python 2 reach end of life?

A: January 1, 2020. Python 2.7.18 (April 2020) was the absolute final release.

Q: Why was the Python 2 to 3 migration so painful?

A: The breaking changes were extensive, many popular libraries were slow to port, the 2to3 tool was imperfect, and organizations had millions of lines of Python 2 code. The migration took over a decade.

Q: What is the "six" library?

A: A Python 2/3 compatibility library by Benjamin Peterson, named because 2 x 3 = 6. It provided utilities to write code that worked on both Python 2 and 3 during the long migration.

Q: What does BDFL stand for, and who held that title?

A: Benevolent Dictator For Life — Guido van Rossum, Python's creator. He held this title until July 2018 when he stepped down after the contentious PEP 572 (walrus operator) debate.

Q: What caused Guido to resign as BDFL?

A: The bitter debate over PEP 572 (the walrus operator :=). Guido was tired of fighting for the PEP and facing personal attacks, so he stepped down in July 2018.

Q: What governance model replaced the BDFL?

A: The Steering Council — a group of 5 people elected by core developers, established by PEP 13. They are re-elected after each major Python release.

Q: What PEP established the Steering Council governance model?

A: PEP 13, "Python Language Governance," adopted in late 2018.

Q: Where has Guido van Rossum worked?

A: CWI Amsterdam (1980s-1995), CNRI (1995-2000), BeOpen (2000), Zope/Digital Creations (2001-2003), Elemental Security (2003-2005), Google (2005-2012), Dropbox (2013-2019), retired briefly, then Microsoft (2020-present).

Q: What did Guido work on at Google?

A: He spent half his time on Python and half on internal Google tools. He helped with the internal code review tool Mondrian and worked on App Engine.

Q: What did Guido work on at Dropbox?

A: He helped improve Dropbox's Python codebase and was involved with type checking and mypy adoption.

Q: Why did Guido join Microsoft in 2020?

A: To work on improving CPython performance. Microsoft funded the "Faster CPython" project that led to significant speed improvements in Python 3.11+.

Q: What does PSF stand for?

A: Python Software Foundation — the non-profit organization that manages the Python programming language, owns its intellectual property, and supports the community.

Q: What is a PEP?

A: Python Enhancement Proposal — a design document providing information or describing a new feature for Python. Key PEPs include PEP 8 (style guide), PEP 20 (Zen of Python), and PEP 484 (type hints).

Q: What PEP defines the Python style guide?

A: PEP 8, "Style Guide for Python Code," originally written by Guido van Rossum, Barry Warsaw, and Alyssa Coghlan.

Q: What PEP number is "The Zen of Python"?

A: PEP 20.

Q: What is the PEP process for proposing language changes?

A: Write a PEP draft, submit it, get a PEP editor to assign a number, discuss it on Python-Dev/Discourse, revise based on feedback, and the Steering Council (or a delegate) accepts, rejects, or defers it.

Q: How does someone become a Python core developer?

A: By sustained contributions to CPython, typically over months or years. An existing core developer nominates them, and the Steering Council votes. Core developers get commit access to the CPython repository.

Q: What is PyCon US?

A: The largest annual gathering for the Python community, organized by the PSF. It includes talks, tutorials, sprints, and an expo hall. It typically attracts 3,000-4,000 attendees.

Q: Where was PyCon US first held?

A: Washington, D.C. in 2003.

Q: What is EuroPython?

A: The largest Python conference in Europe, held annually since 2002. It rotates between European cities.

Q: What is PyData?

A: A conference series (with events worldwide) focused on data science, machine learning, and analytics in the Python ecosystem. Organized by NumFOCUS.

Q: What are "sprints" at Python conferences?

A: Multi-day coding sessions after the main conference where attendees collaborate on open-source projects, fix bugs, and contribute to Python itself.

Q: What are Python "lightning talks"?

A: Very short (typically 5-minute) presentations given at Python conferences, often humorous or covering niche topics.

Q: What is CPython?

A: The reference implementation of Python, written in C. When people say "Python," they usually mean CPython.

Q: Name five alternative Python implementations.

A: PyPy (JIT-compiled, faster), Jython (runs on JVM), IronPython (runs on .NET), GraalPython (on GraalVM), and MicroPython (for microcontrollers).

Q: What is PyPy and why is it significant?

A: A Python implementation with a Just-In-Time (JIT) compiler that can be 4-10x faster than CPython for long-running programs. It is written in RPython (a restricted subset of Python).

Q: What is MicroPython?

A: A lean Python 3 implementation designed to run on microcontrollers and constrained environments. It implements a subset of the standard library optimized for embedded systems.

Q: What is Timsort?

A: The sorting algorithm used by Python's sorted() and list.sort(). Designed by Tim Peters in 2002, it is a hybrid merge sort/insertion sort with O(n log n) worst case and O(n) best case for partially sorted data. Adopted by Java, Android, and other platforms.

Q: What was Python 1.5 notable for?

A: Released in 1998, it was the version that really established Python's popularity and was the standard for many years. It introduced the re module replacing the older regex module.

Q: What did Python 2.2 introduce?

A: New-style classes (unifying types and classes), iterators, generators (PEP 255), and the __future__ mechanism. It was one of the most significant Python 2.x releases.

Q: What did Python 2.5 introduce?

A: The with statement (PEP 343), conditional expressions (x if cond else y), and try/except/finally as a single statement.

Q: What did Python 2.6 introduce?

A: It served as a transition release toward Python 3, adding many Python 3 features with backward compatibility. It introduced the multiprocessing module and the -3 flag for warnings about Python 3 incompatibilities.

Q: What did Python 2.7 introduce?

A: The final Python 2 release. It added set literals {1, 2, 3}, dict comprehensions, OrderedDict, Counter, and the argparse module.

Q: What is the significance of Python 3.6?

A: It added f-strings (PEP 498), variable annotations (PEP 526), underscores in numeric literals, the secrets module, async generators, and dict ordering as an implementation detail.

Q: What did Python 3.7 add?

A: dataclasses, breakpoint(), asyncio.run(), contextvars, postponed evaluation of annotations (PEP 563 as __future__), and dict ordering became a language guarantee.

Q: What year did Guido van Rossum receive the Award for the Advancement of Free Software from the FSF?

A: 2001.

Q: What is CWI?

A: Centrum Wiskunde & Informatica (Center for Mathematics and Computer Science) in Amsterdam, the Netherlands. This is where Guido created Python.

Q: What was the "Python 3000" or "Py3k" initiative?

A: The long-term project to create Python 3, which was known as "Python 3000" during development. The name was a tongue-in-cheek suggestion that it would take until the year 3000 to finish.


2. Language Fundamentals

Q: What is the difference between is and == in Python?

A: is checks identity (same object in memory). == checks equality (same value). Due to integer caching, a is b might be True for small integers but this should never be relied upon.

Q: What integers does CPython cache (intern)?

A: Integers from -5 to 256 inclusive. These are pre-allocated singleton objects, so a = 256; b = 256; a is b is True, but a = 257; b = 257; a is b may be False.

Q: Does Python intern strings?

A: CPython interns some strings automatically (like identifiers and string literals that look like identifiers). You can also explicitly intern with sys.intern(). Interning allows is comparison instead of == for speed.

Q: What is "duck typing"?

A: "If it walks like a duck and quacks like a duck, it's a duck." Python checks behavior (methods/attributes) rather than explicit type, enabling polymorphism without inheritance.

Q: What is "EAFP" in Python?

A: "Easier to Ask Forgiveness than Permission" — a coding style that tries an operation and handles exceptions rather than checking preconditions. Contrasted with "LBYL" (Look Before You Leap).

Q: What is the LEGB rule?

A: The variable scoping rule in Python: Local, Enclosing, Global, Built-in. Python searches for names in this order.

Q: What is a list comprehension and when was it introduced?

A: A concise syntax for creating lists: [x**2 for x in range(10)]. Introduced in Python 2.0 (PEP 202), inspired by Haskell.

Q: What are the different comprehension types in Python?

A: List [x for x in items], set {x for x in items}, dict {k: v for k, v in pairs}, and generator expression (x for x in items).

Q: What is the difference between a list comprehension and a generator expression?

A: A list comprehension [x for x in items] creates the entire list in memory. A generator expression (x for x in items) produces values lazily, one at a time, using much less memory for large sequences.

Q: What is the result of bool([])?

A: False. Empty sequences (list, tuple, string, dict, set) are falsy.

Q: What is the result of True + True?

A: 2. In Python, bool is a subclass of int, where True is 1 and False is 0.

Q: What does isinstance(True, int) return?

A: True, because bool is a subclass of int.

Q: What is the truthiness rule in Python?

A: Objects are truthy by default. The following are falsy: None, False, zero of any numeric type (0, 0.0, 0j, Decimal(0), Fraction(0, 1)), empty sequences/mappings ('', (), [], {}, set(), range(0)), and objects whose __bool__ returns False or __len__ returns 0.

Q: What does if __name__ == '__main__': do?

A: It checks whether the script is being run directly (not imported). Code in this block only executes when the file is the entry point, not when imported as a module.

Q: What is __all__ used for in a module?

A: It defines the public API — the list of names exported when someone does from module import *. If not defined, all names not starting with underscore are exported.

Q: What is sys.path and how does Python use it?

A: A list of directories that Python searches when importing modules. It includes the script's directory, PYTHONPATH environment variable entries, and default library paths.

Q: What is the nonlocal keyword used for?

A: It declares that a variable in an inner function refers to a variable in the enclosing (non-global) scope, allowing it to be modified. Without nonlocal, the inner function would create a new local variable.

Q: What is the global keyword used for?

A: It declares that a variable inside a function refers to the global (module-level) scope, allowing it to be read and modified.

Q: What is monkey patching?

A: Dynamically modifying a class or module at runtime. For example, replacing a method on an existing class. It is powerful but can make code hard to debug.

Q: What does id() return?

A: The identity of an object — an integer guaranteed to be unique for that object during its lifetime. In CPython, it is the memory address.

Q: What is the del statement?

A: It unbinds a name from an object: del x removes x from the local namespace. For lists, del lst[i] removes an element. del does not directly free memory — it just decrements the reference count.

Q: What is the maximum recursion depth in Python by default?

A: 1000. It can be changed with sys.setrecursionlimit(), but deep recursion is discouraged due to stack overflow risk.

Q: What is the Ellipsis object (...) used for in Python?

A: As a placeholder in stubs/protocols (def method(self) -> None: ...), in NumPy for advanced slicing (array[..., 0]), and in type hints (tuple[int, ...] for variable-length tuples).

Q: What does type(...) return?

A: <class 'ellipsis'>. The ... literal is the singleton Ellipsis object.

Q: What is the NotImplemented singleton used for?

A: Rich comparison methods return NotImplemented to indicate they don't support comparison with the given type, allowing Python to try the reflected operation on the other operand. It is NOT the same as NotImplementedError.

Q: What is NotImplemented vs NotImplementedError?

A: NotImplemented is a singleton value returned by rich comparison methods to signal the comparison is not implemented for those types. NotImplementedError is an exception raised to indicate an abstract method needs to be overridden.

Q: What does the __future__ module do?

A: It enables features from future Python versions in the current version. For example, from __future__ import annotations (PEP 563) makes all annotations strings by default (lazy evaluation).

Q: What is the Python REPL's _ variable?

A: In the interactive interpreter, _ holds the result of the last expression evaluated. For example, after typing 2 + 3, _ equals 5.

Q: What does sorted() guarantee about equal elements?

A: The sort is stable — elements that compare equal retain their original relative order.

Q: What does [1, 2, 3][::-1] return?

A: [3, 2, 1] — a reversed copy of the list. The [::-1] slice reverses any sequence.

Q: What is the result of "hello" * 3?

A: 'hellohellohello'. String (and sequence) multiplication repeats the sequence.

Q: What does any([]) return?

A: False. any of an empty iterable is False. all([]) returns True (vacuous truth).

Q: Why does all([]) return True?

A: It follows the mathematical convention of vacuous truth — the statement "all elements satisfy the condition" is trivially true when there are no elements.

Q: What does string.ascii_letters contain?

A: All ASCII letters: 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.

Q: What is the difference between a += b and a = a + b for lists?

A: For lists, += modifies the list in-place (calls __iadd__), while a = a + b creates a new list. This matters when other variables reference the same list.

Q: What does enumerate() return?

A: An iterator of (index, element) tuples. It accepts an optional start parameter: enumerate(items, start=1).

Q: What is the zip() function's strict mode?

A: Added in Python 3.10 (PEP 618): zip(*iterables, strict=True) raises ValueError if the iterables have different lengths.

Q: What is the walrus operator in Python?

A: The := assignment expression operator, introduced in Python 3.8 (PEP 572). It assigns a value to a variable as part of an expression.

Q: Give a common use case for the walrus operator.

A: In while loops reading input: while (line := input()) != 'quit': process(line). Or in list comprehensions for filtering: [y for x in data if (y := f(x)) > 0].

Q: Why was PEP 572 (walrus operator) controversial?

A: It sparked intense debate about readability and Pythonic style. The contentious discussion led to Guido van Rossum resigning as BDFL in July 2018, stating he was tired of fighting for the PEP and facing personal attacks.

Q: Can the walrus operator be used in all expression contexts?

A: No. It cannot be used as a top-level statement (use regular = instead). It also has restrictions in comprehension scoping and augmented assignments.

Q: What is the precedence of the walrus operator?

A: It has very low precedence — lower than most operators. Parentheses are often needed: if (n := len(data)) > 10: requires the parentheses around the assignment.

Q: What is the difference between bytes and str in Python 3?

A: str holds Unicode text, bytes holds raw binary data. They are distinct types and cannot be mixed without explicit encoding/decoding.

Q: What encoding does Python 3 use for source files by default?

A: UTF-8 (since Python 3.0). Python 2 defaulted to ASCII.

Q: What is a bytearray and how does it differ from bytes?

A: bytearray is a mutable sequence of bytes, while bytes is immutable. bytearray supports in-place modification.

Q: What does pass do in Python?

A: It is a null operation — a placeholder that does nothing. It is used where a statement is syntactically required but no action is needed (empty class bodies, stubs, etc.).

Q: What is the difference between None and False?

A: None is the singleton representing absence of a value (NoneType). False is a boolean. Both are falsy, but None is not False evaluates to True.

Q: How do you check for None in Python?

A: Always use is None or is not None, never == None. The is operator checks identity, which is correct since None is a singleton.


3. Data Structures

Q: What are the advantages of collections.deque over a list?

A: O(1) append and pop from both ends (lists are O(n) for insert(0, x) and pop(0)). Deques also support a maxlen parameter for fixed-size buffers.

Q: What does deque.rotate(n) do?

A: Rotates the deque n steps to the right. If n is negative, it rotates to the left. For example, deque([1,2,3]).rotate(1) gives deque([3,1,2]).

Q: What does collections.deque(maxlen=n) do when you append beyond capacity?

A: It automatically discards elements from the opposite end. Appending to the right discards from the left, and vice versa. This creates a bounded buffer.

Q: What does collections.Counter return when you access a key that doesn't exist?

A: It returns 0 (not a KeyError), because Counter is a subclass of dict that overrides __missing__ to return zero.

Q: What does Counter.most_common(n) return?

A: A list of the n most common elements and their counts, as (element, count) tuples, sorted from most common to least.

Q: What happens when you add two Counter objects together?

A: Their counts are summed element-wise. Subtraction (-) subtracts counts and drops zero/negative results. The & operator gives element-wise minimums (intersection) and | gives maximums (union).

Q: What does Counter.elements() return?

A: An iterator over elements, each repeated as many times as its count. Elements with zero or negative counts are excluded.

Q: What does collections.Counter.subtract() do differently from -?

A: subtract() subtracts counts in-place and allows negative results. The - operator drops zero and negative results.

Q: What is the default value returned by a defaultdict(list) for a missing key?

A: An empty list []. The argument to defaultdict is a factory function called with no arguments to produce default values.

Q: What happens if you create a defaultdict with no argument (i.e., defaultdict())?

A: Accessing a missing key raises a KeyError, just like a regular dict, because the default_factory is None.

Q: What method does defaultdict call to produce a default value?

A: It calls the default_factory attribute, which is the callable passed to the constructor. This is invoked from the __missing__ method.

Q: Is OrderedDict still useful now that regular dicts maintain insertion order (since Python 3.7)?

A: Yes. OrderedDict supports move_to_end(), equality comparisons consider order (unlike regular dicts), and it has a different __eq__ behavior: two OrderedDicts with the same items in different order are not equal, while two regular dicts would be.

Q: What does OrderedDict.move_to_end(key, last=True) do?

A: It moves an existing key to either end of the ordered dict. With last=True (default) it moves to the right end; with last=False to the beginning.

Q: What is collections.ChainMap used for?

A: It groups multiple dicts into a single mapping view. Lookups search the underlying maps in order. It is commonly used for managing nested scopes like configuration layers.

Q: When you set a value on a ChainMap, which underlying dict is modified?

A: Only the first (frontmost) mapping in the chain. Lookups search all maps, but mutations only affect maps[0].

Q: How do you create a named tuple with collections.namedtuple?

A: Point = namedtuple('Point', ['x', 'y']) or equivalently with a space-separated string 'x y'. Instances are immutable tuples with named fields.

Q: What method on a namedtuple returns a regular dictionary?

A: ._asdict(). Despite the leading underscore, it is part of the public API — the underscore prevents name conflicts with field names.

Q: What method on a namedtuple creates a new instance with some fields replaced?

A: ._replace(**kwargs). It returns a new instance since namedtuples are immutable.

Q: What is collections.UserDict for?

A: It is a wrapper around a regular dict (stored as .data) designed to be subclassed. It is easier to subclass than dict because you only need to override the methods you want without worrying about internal C optimizations.

Q: What is collections.abc and how does it differ from collections?

A: collections.abc contains abstract base classes for containers (like Mapping, Sequence, Iterable, MutableSet). These were moved from collections in Python 3.3 and accessing them from collections directly was deprecated in 3.9 and removed in 3.10.

Q: Can a tuple be a dictionary key?

A: Only if all its elements are hashable. (1, 2, 3) can be a key, but (1, [2, 3]) cannot because lists are unhashable.

Q: What is a frozenset?

A: An immutable version of set. Since it is hashable, it can be used as a dictionary key or as an element of another set.

Q: What is the result of {} == set()?

A: False. {} creates an empty dict, not an empty set. To create an empty set, you must use set().

Q: What is the type of {}?

A: dict. This is a common gotcha — empty curly braces create a dict, not a set.

Q: What is the time complexity of Python's dict lookup?

A: Average O(1), worst case O(n) due to hash collisions. Python uses open addressing with random probing for collision resolution.

Q: When did dict ordering become a language guarantee?

A: Python 3.7 (it was an implementation detail in CPython 3.6). Dicts maintain insertion order as part of the language spec.

Q: How does CPython implement dicts internally?

A: Using a compact hash table with two arrays: a sparse index array and a dense key-value array. This design (introduced in CPython 3.6) saves 20-25% memory compared to the old implementation.

Q: What is the time complexity of list.append()?

A: Amortized O(1). Lists over-allocate memory, so most appends are O(1), with occasional O(n) resizes.

Q: What is the time complexity of list.insert(0, x)?

A: O(n), because all existing elements must be shifted right.

Q: What is the time complexity of in for lists vs sets?

A: O(n) for lists (linear scan), O(1) average for sets (hash lookup).

Q: What is the array module used for?

A: It provides space-efficient arrays of uniform C-style types (like 'i' for int, 'f' for float). More memory-efficient than lists for large homogeneous numeric data, but less flexible.

Q: What does sys.getsizeof(()) vs sys.getsizeof([]) show?

A: Empty tuples are smaller than empty lists in memory. An empty tuple is about 40 bytes; an empty list is about 56 bytes (on 64-bit CPython), because lists have extra overhead for mutability (over-allocation buffer).

Q: Why are tuples slightly faster than lists?

A: Tuples are immutable, so CPython can optimize their storage (contiguous memory, no over-allocation). Small tuples (up to length 20) are also cached and reused by the free-list allocator.

Q: What does list.sort() vs sorted() return?

A: list.sort() sorts in-place and returns None. sorted() returns a new sorted list and works on any iterable.


4. Functions & Closures

Q: What is the difference between *args and **kwargs?

A: *args collects extra positional arguments into a tuple. **kwargs collects extra keyword arguments into a dictionary. Together they allow functions to accept any combination of arguments.

Q: What does the * separator in function parameters do?

A: Parameters after * are keyword-only: def f(a, *, b): means b must be passed as a keyword argument. Added in Python 3.0.

Q: What does the / separator in function parameters do?

A: Introduced in Python 3.8 (PEP 570), parameters before / are positional-only: def f(a, /, b): means a must be passed positionally.

Q: What is a closure in Python?

A: A function that captures variables from its enclosing scope. The inner function "closes over" the variables, retaining access even after the enclosing function has returned.

Q: What is the mutable default argument gotcha?

A: Default arguments are evaluated once at function definition time, not each call. So def f(x=[]): shares the same list across all calls. Use None and create the list inside the function instead.

Q: What is the late binding closures gotcha?

A: Closures capture variables by reference, not value. In a loop for i in range(3): funcs.append(lambda: i), all lambdas return 2 (the final value of i). Fix with default arguments: lambda i=i: i.

Q: What is a lambda function?

A: An anonymous inline function limited to a single expression: lambda x, y: x + y. It cannot contain statements or annotations.

Q: What are first-class functions?

A: In Python, functions are objects — they can be assigned to variables, passed as arguments, returned from other functions, and stored in data structures.

Q: What is a higher-order function?

A: A function that takes another function as an argument or returns a function. map(), filter(), sorted() (with key), and decorators are examples.

Q: What is a decorator in Python?

A: Syntactic sugar for wrapping a function or class: @decorator above a definition is equivalent to func = decorator(func). Decorators can add behavior, modify, or replace the decorated object.

Q: How do you stack multiple decorators?

A: Apply them one above another: @decorator1 then @decorator2 above def func. This is equivalent to func = decorator1(decorator2(func)) — the bottommost decorator is applied first.

Q: What is a parameterized decorator?

A: A decorator that takes arguments: @retry(max_attempts=3). It is implemented as a function that returns a decorator, creating a three-level nesting pattern (decorator factory -> decorator -> wrapper).

Q: What does functools.wraps do?

A: It is a decorator for wrapper functions that copies metadata (like __name__, __doc__, __module__, __qualname__, __annotations__, and __dict__) from the wrapped function to the wrapper, preserving introspection.

Q: What does @functools.wraps(func) actually copy from func to the wrapper?

A: It copies __module__, __name__, __qualname__, __annotations__, __doc__, and updates __dict__. It also sets __wrapped__ to point to the original function.


5. OOP & Classes

Q: What does __init__ vs __new__ do?

A: __new__ creates and returns a new instance (it is a static method on the class). __init__ initializes the instance after creation. __new__ is called first and is rarely overridden except for immutable types or singletons.

Q: What is __slots__ and why use it?

A: A class variable that explicitly declares instance attributes, replacing __dict__. It saves memory (no per-instance dict) and slightly speeds up attribute access. Instances cannot have attributes not listed in __slots__.

Q: What are descriptors in Python?

A: Objects that define __get__, __set__, or __delete__ methods. They control attribute access on classes. Properties, methods, classmethods, and staticmethods are all implemented using descriptors.

Q: What is a data descriptor vs a non-data descriptor?

A: A data descriptor defines both __get__ and __set__ (or __delete__). A non-data descriptor defines only __get__. Data descriptors take priority over instance __dict__, while non-data descriptors do not.

Q: What is the MRO in Python?

A: Method Resolution Order — the order in which base classes are searched when looking up a method. Python uses the C3 linearization algorithm. You can see it with ClassName.__mro__ or ClassName.mro().

Q: What is C3 linearization?

A: The algorithm Python uses to determine MRO for multiple inheritance. It preserves local precedence order and monotonicity, ensuring a consistent and predictable method resolution.

Q: What is a metaclass?

A: A class whose instances are themselves classes. type is the default metaclass in Python. Metaclasses control class creation and can customize the behavior of class statements.

Q: What is the relationship between type and object?

A: object is the base class of all classes (including type), and type is the metaclass of all classes (including object). So type is an instance of itself, and object is an instance of type.

Q: What is the difference between @staticmethod and @classmethod?

A: @staticmethod receives no implicit first argument — it is just a regular function namespaced to the class. @classmethod receives the class as its first argument (cls), so it can access class-level data and be properly inherited.

Q: What is __init_subclass__ used for?

A: A hook method called when a class is subclassed. It allows the parent class to customize subclass creation without a metaclass. Added in Python 3.6 (PEP 487).

Q: What is __class_getitem__ used for?

A: It enables the subscript syntax for classes: MyClass[int]. Used to make classes generic without metaclasses. Added in Python 3.7 (PEP 560).

Q: What is name mangling in Python?

A: Attributes starting with __ (double underscore) but not ending with __ are name-mangled: __attr in class MyClass becomes _MyClass__attr. This provides a limited form of name privacy to avoid accidental name clashes in subclasses.

Q: What module provides abstract base classes?

A: The abc module, with ABC as a base class and @abstractmethod as a decorator.

Q: What does @dataclass generate automatically?

A: By default, __init__, __repr__, and __eq__ methods. With additional parameters it can generate __hash__, ordering methods, and use __slots__.

Q: What is @dataclass an example of in terms of Python internals?

A: A class decorator that uses code generation — it inspects annotations and generates __init__, __repr__, __eq__, and other methods at class definition time.

Q: What does @dataclass(frozen=True) do?

A: It makes instances of the dataclass immutable (read-only). Attempting to assign to fields after creation raises FrozenInstanceError. Frozen dataclasses are also hashable by default.

Q: What parameter to @dataclass was added in Python 3.10 to allow slot-based instances?

A: slots=True. When set, the generated class uses __slots__ instead of __dict__, resulting in faster attribute access and less memory usage.

Q: What does @dataclass(kw_only=True) do, introduced in Python 3.10?

A: It makes all fields keyword-only in the generated __init__, so they cannot be passed as positional arguments.

Q: What method can you define on a dataclass to customize how it is initialized after __init__?

A: __post_init__(). It is called automatically after the generated __init__ and is useful for validation or computing derived fields.

Q: What does the dataclasses.asdict() function do?

A: It recursively converts a dataclass instance into a dictionary. There is also astuple() for converting to a tuple.

Q: In dataclasses, what does the field() function's default_factory parameter do?

A: It provides a zero-argument callable that creates the default value for the field. This is necessary for mutable defaults like lists or dicts to avoid the shared mutable default argument problem.

Q: What is the dataclasses.field() metadata parameter for?

A: It is a mapping that stores arbitrary user-defined data on the field. It is not used by dataclasses itself but can be consumed by third-party libraries or custom processing.

Q: What does @dataclass(order=True) do?

A: It generates __lt__, __le__, __gt__, and __ge__ methods that compare instances as if they were tuples of their fields (in order of definition).

Q: What is typing.NamedTuple and how does it compare to collections.namedtuple?

A: typing.NamedTuple is a class-based syntax for named tuples that supports type annotations: class Point(NamedTuple): x: int; y: int. It is more readable and type-checker-friendly than the functional namedtuple() form.

Q: What is the match statement's __match_args__ attribute used for?

A: It defines the positional pattern matching order for a class. For example, __match_args__ = ('x', 'y') allows case Point(1, 2) instead of requiring case Point(x=1, y=2).

Q: What is __set_name__ used for?

A: Called on descriptors when a class is created, it receives the owner class and the attribute name. This allows descriptors to know what name they were assigned to without the user specifying it explicitly. Added in Python 3.6.

Q: What is the property built-in?

A: A descriptor that lets you define getter, setter, and deleter methods for an attribute. It provides a Pythonic alternative to Java-style getter/setter methods: @property for the getter, @attr.setter for the setter.


6. Iterators, Generators & Functional

Q: What is a generator in Python?

A: A function that uses yield to produce a series of values lazily. Calling the function returns a generator iterator. Generators are memory-efficient for large sequences.

Q: What is yield from used for?

A: Introduced in Python 3.3 (PEP 380), it delegates to a sub-generator: yield from iterable is equivalent to for item in iterable: yield item but also properly handles send(), throw(), and return values.

Q: What does the __iter__ method return?

A: An iterator object (which must implement __next__). If a class defines __iter__ and __next__, its instances are iterators. If it only defines __iter__, it is iterable.

Q: What is the iterator protocol?

A: An object must implement __iter__() (returning itself) and __next__() (returning the next value or raising StopIteration).

Q: What does itertools.chain(*iterables) do?

A: It chains multiple iterables together into a single lazy iterator, yielding all elements from the first iterable, then the second, and so on.

Q: What is the difference between itertools.chain() and itertools.chain.from_iterable()?

A: chain() takes multiple iterables as separate arguments: chain([1,2], [3,4]). chain.from_iterable() takes a single iterable of iterables: chain.from_iterable([[1,2], [3,4]]). The latter is useful when you have a generator of iterables.

Q: What does itertools.combinations('ABCD', 2) return?

A: An iterator of 2-element tuples containing all unique combinations without repetition: ('A','B'), ('A','C'), ('A','D'), ('B','C'), ('B','D'), ('C','D').

Q: What is the difference between combinations and combinations_with_replacement?

A: combinations does not allow repeated elements, while combinations_with_replacement does. For example, combinations_with_replacement('AB', 2) yields ('A','A'), ('A','B'), ('B','B').

Q: How many items does itertools.permutations('ABC', 2) yield?

A: 6 items: ('A','B'), ('A','C'), ('B','A'), ('B','C'), ('C','A'), ('C','B') — all ordered arrangements of 2 elements from 3. The formula is P(3,2) = 3!/(3-2)! = 6.

Q: What does itertools.product('AB', '12') yield?

A: The Cartesian product: ('A','1'), ('A','2'), ('B','1'), ('B','2'). It is equivalent to nested for loops.

Q: How do you use itertools.product to get the equivalent of a triple nested loop?

A: itertools.product(range(3), range(3), range(3)) yields all 27 triples, equivalent to three nested for loops.

Q: What does itertools.product('AB', repeat=3) produce?

A: All 8 three-element tuples from the Cartesian product of 'AB' with itself 3 times, equivalent to product('AB', 'AB', 'AB').

Q: What critical requirement does itertools.groupby() have?

A: The input must be sorted (or at least grouped) by the key function. groupby only groups consecutive elements with the same key. If the data is not pre-sorted, elements with the same key will appear in separate groups.

Q: What does itertools.groupby() yield?

A: Pairs of (key, group_iterator) where the group iterator yields all consecutive elements with that key. The group iterators share the underlying iterator, so you must consume each group before advancing to the next.

Q: What does itertools.zip_longest() do differently from zip()?

A: zip() stops at the shortest iterable. zip_longest() continues until the longest iterable is exhausted, filling missing values with a fillvalue (default None).

Q: What does itertools.starmap(func, iterable) do?

A: It applies func to each element of the iterable using argument unpacking. For example, starmap(pow, [(2,3), (3,2)]) yields 8, 9.

Q: What does itertools.tee(iterable, n=2) return?

A: n independent iterators from a single iterable. Once teed, the original iterator should not be used. Note: it can consume significant memory if one copy advances far ahead of the others.

Q: What does itertools.count(start=0, step=1) do?

A: It creates an infinite iterator that yields evenly spaced values starting from start. For example, count(10, 2) yields 10, 12, 14, 16, ....

Q: What does itertools.cycle(iterable) do?

A: It creates an infinite iterator that cycles through the elements of the iterable. For example, cycle('ABC') yields A, B, C, A, B, C, A, ....

Q: What does itertools.repeat(elem, times=None) do?

A: It yields elem over and over, either infinitely (if times is None) or the specified number of times.

Q: What does itertools.islice() do?

A: It slices an iterator lazily, similar to sequence slicing but works on any iterable and doesn't support negative indices. islice(iterable, stop) or islice(iterable, start, stop, step).

Q: What does itertools.dropwhile(predicate, iterable) do?

A: It drops elements from the beginning of the iterable as long as the predicate is true, then yields all remaining elements (even if the predicate becomes true again later).

Q: What does itertools.takewhile(predicate, iterable) do?

A: It yields elements from the beginning as long as the predicate is true, then stops entirely at the first false element.

Q: What does itertools.accumulate() do?

A: It yields running totals (or running results of any binary function). For example, accumulate([1,2,3,4]) yields 1, 3, 6, 10. You can pass a function like operator.mul for running products.

Q: What does itertools.compress(data, selectors) do?

A: It filters data by returning only the elements where the corresponding selector is truthy. For example, compress('ABCDEF', [1,0,1,0,1,1]) yields A, C, E, F.

Q: What does itertools.filterfalse(predicate, iterable) do?

A: It yields elements for which the predicate returns false — the opposite of the built-in filter().

Q: What is itertools.pairwise() and when was it added?

A: Added in Python 3.10, it yields consecutive overlapping pairs from an iterable. pairwise('ABCD') yields ('A','B'), ('B','C'), ('C','D').

Q: What does itertools.pairwise() return for an empty or single-element iterable?

A: An empty iterator — there are no pairs to form.

Q: What does itertools.batched() do, and when was it added?

A: Added in Python 3.12, it yields non-overlapping batches (tuples) of a given size from an iterable. batched('ABCDEFG', 3) yields ('A','B','C'), ('D','E','F'), ('G',).

Q: What does functools.lru_cache do?

A: It is a decorator that caches the results of a function using a Least Recently Used eviction policy. By default, it caches up to 128 results. Use @lru_cache(maxsize=None) for unbounded caching.

Q: What is the difference between functools.lru_cache and functools.cache?

A: functools.cache (added in Python 3.9) is equivalent to lru_cache(maxsize=None) — an unbounded cache with no LRU eviction. It is simpler and slightly faster when you don't need size limits.

Q: What method on an lru_cache-decorated function shows cache performance?

A: .cache_info() returns a named tuple with hits, misses, maxsize, and currsize. You can also call .cache_clear() to reset the cache.

Q: Why must arguments to an lru_cache-decorated function be hashable?

A: Because the cache uses a dictionary internally, and dictionary keys must be hashable. Passing unhashable arguments like lists will raise a TypeError.

Q: What is the lru_cache maximum size by default?

A: 128 entries.

Q: What does functools.partial do?

A: It creates a new callable with some arguments of the original function pre-filled. For example, int_from_binary = partial(int, base=2) creates a function that parses binary strings.

Q: What does functools.reduce do?

A: It applies a two-argument function cumulatively to the items of an iterable, reducing it to a single value. For example, reduce(operator.add, [1,2,3,4]) returns 10.

Q: Why was reduce moved from builtins to functools in Python 3?

A: Guido van Rossum argued that reduce() is confusing and rarely needed. He preferred explicit loops for clarity. It was moved to functools to discourage casual use.

Q: What does functools.singledispatch do?

A: It provides single-dispatch generic functions — function overloading based on the type of the first argument. You register implementations for different types using @func.register(type).

Q: What is functools.singledispatchmethod used for?

A: It is the method version of singledispatch for use inside classes. It dispatches based on the type of the first non-self/non-cls argument.

Q: What does functools.cached_property do?

A: It transforms a method into a property that is computed once and then cached as a normal attribute. Unlike @property, the computation only runs on the first access.

Q: When was functools.cached_property introduced?

A: Python 3.8.

Q: What does functools.cmp_to_key do?

A: It converts an old-style comparison function (that returns -1, 0, or 1) into a key function suitable for sorted(), min(), max(), etc. This bridges the gap from Python 2's cmp parameter.

Q: What does @functools.total_ordering do?

A: It is a class decorator that, given __eq__ and one of __lt__, __le__, __gt__, or __ge__, automatically generates the remaining comparison methods.

Q: What does functools.total_ordering require you to define?

A: You must define __eq__ and one of the other comparison methods (__lt__, __le__, __gt__, or __ge__). The decorator fills in the rest.

Q: What does functools.partialmethod do?

A: Like partial but for methods in a class. It creates a partial version of a method that can be used as a descriptor.

Q: What is functools.update_wrapper() and how does it relate to functools.wraps?

A: update_wrapper() is the function that does the actual work. functools.wraps is a convenience decorator that calls update_wrapper().

Q: What is operator.itemgetter() used for?

A: It creates a callable that retrieves items by index or key: itemgetter(1) is equivalent to lambda x: x[1]. Commonly used as a key function for sorted().

Q: What is operator.attrgetter() used for?

A: Similar to itemgetter but for attributes: attrgetter('name') is equivalent to lambda x: x.name. Supports dotted names for nested attributes.

Q: What is operator.methodcaller() used for?

A: It creates a callable that calls a method: methodcaller('lower') is equivalent to lambda x: x.lower(). Can also pass arguments.

Q: What built-in functions are considered functional-style?

A: map(), filter(), zip(), enumerate(), sorted(), reversed(), min(), max(), sum(), any(), all().


7. Error Handling

Q: What is the order of clauses in a try statement?

A: try -> except (zero or more) -> else (optional, runs if no exception) -> finally (optional, always runs). The else block executes only when no exception was raised in try.

Q: When does the else clause of a try block execute?

A: Only when no exception was raised in the try block. It is useful for code that should run only on success, keeping the try block minimal.

Q: Does finally always execute?

A: Yes, even if there is a return, break, or continue in the try or except blocks. The only exception is if the process is killed by the OS or os._exit() is called.

Q: What is exception chaining in Python?

A: When an exception is raised inside an except block, the original exception is stored in __context__. You can explicitly chain with raise NewException() from original which sets __cause__.

Q: What is the difference between __cause__ and __context__ on exceptions?

A: __cause__ is set explicitly via raise X from Y (explicit chaining). __context__ is set automatically when an exception is raised during exception handling (implicit chaining).

Q: How do you suppress exception chaining?

A: Use raise NewException() from None. This sets __cause__ to None and __suppress_context__ to True.

Q: What is the exception hierarchy's root in Python?

A: BaseException. It has four direct subclasses: SystemExit, KeyboardInterrupt, GeneratorExit, and Exception. User code should generally catch/subclass Exception, not BaseException.

Q: Why should you not catch BaseException?

A: Because it would catch SystemExit (preventing clean exit), KeyboardInterrupt (preventing Ctrl+C), and GeneratorExit. Catch Exception instead for general error handling.

Q: What are exception groups, introduced in Python 3.11?

A: ExceptionGroup and BaseExceptionGroup allow raising and handling multiple unrelated exceptions simultaneously. They are caught with the new except* syntax.

Q: What is the except* syntax?

A: Introduced in Python 3.11, it handles exception groups. except* ValueError as eg: catches all ValueError instances from an exception group while letting other exceptions propagate.

Q: What is the LBYL coding style?

A: "Look Before You Leap" — checking preconditions before an operation (e.g., if key in dict: dict[key]). Python generally prefers EAFP, but LBYL is sometimes clearer for non-exceptional conditions.

Q: How do you create a custom exception?

A: Subclass Exception (or a more specific built-in exception): class MyError(Exception): pass. You can add custom attributes in __init__.

Q: What does raise without an argument do?

A: It re-raises the current exception being handled. It can only be used inside an except block.

Q: What improvement did Python 3.11 make to error messages?

A: Much more precise error locations. Tracebacks now point to the exact expression that caused the error, not just the line. For example, in a['x']['y']['z'], the traceback highlights which dictionary access failed.


8. Standard Library Deep Cuts

Q: What module provides functions to maintain a list in sorted order without having to sort the list after each insertion?

A: The bisect module. It uses binary search via bisect.insort() and bisect.bisect() to efficiently insert into and search sorted lists.

Q: What is the time complexity of bisect.insort() for inserting into a sorted list?

A: O(n) overall — O(log n) for the binary search to find the insertion point, but O(n) for the actual insertion due to shifting elements in the list.

Q: What is the difference between bisect.bisect_left() and bisect.bisect_right()?

A: bisect_left() returns the leftmost position where an element can be inserted to keep the list sorted (before any existing equal elements), while bisect_right() returns the rightmost position (after existing equal elements). bisect() is an alias for bisect_right().

Q: Which standard library module provides a min-heap implementation?

A: The heapq module. Python's heapq only implements a min-heap natively; for a max-heap you negate values or use a wrapper.

Q: How do you implement a max-heap using Python's heapq module?

A: By negating the values before pushing and after popping, e.g., heapq.heappush(heap, -value) and -heapq.heappop(heap).

Q: What does heapq.nlargest(n, iterable) do, and when is it more efficient than sorting?

A: It returns the n largest elements from an iterable. It is more efficient than full sorting when n is small relative to the iterable size, using a min-heap of size n internally.

Q: What function in heapq merges multiple sorted inputs into a single sorted output?

A: heapq.merge(*iterables). It returns a lazy iterator, making it memory-efficient for merging sorted streams.

Q: What does contextlib.suppress() do?

A: It is a context manager that suppresses specified exceptions. For example, with contextlib.suppress(FileNotFoundError): os.remove('file') silently ignores the error if the file doesn't exist.

Q: What is contextlib.ExitStack used for?

A: It is a context manager that manages a dynamic collection of other context managers and cleanup functions. It is useful when you don't know at coding time how many context managers you need.

Q: How do you create a context manager from a generator function using contextlib?

A: Use the @contextlib.contextmanager decorator on a generator function that yields exactly once. Code before the yield is the setup (__enter__), and code after is the teardown (__exit__).

Q: What does contextlib.redirect_stdout() do?

A: It temporarily redirects sys.stdout to another file-like object within a with block. There is also redirect_stderr() for standard error.

Q: What is the contextlib.asynccontextmanager decorator for?

A: It is the async equivalent of @contextmanager, allowing you to create async context managers from async generator functions that yield once.

Q: What is the contextlib.nullcontext() used for?

A: It is a no-op context manager, useful as a stand-in when a context manager is expected but none is needed. Added in Python 3.7.

Q: What is the enum.auto() function used for?

A: It automatically generates values for enum members, typically incrementing integers starting from 1. The behavior can be customized by overriding _generate_next_value_().

Q: What is the difference between enum.Enum and enum.IntEnum?

A: IntEnum members are also integers and can be compared with plain ints and used anywhere an int is expected. Enum members are not comparable with ints — they can only be compared with other members of the same enum.

Q: What Enum subclass was introduced in Python 3.11 to ensure members are valid strings?

A: enum.StrEnum. Its members are also strings and can be used wherever strings are expected.

Q: What does the enum.Flag class allow?

A: It supports bitwise operations (|, &, ^, ~) on enum members, allowing them to be combined as bit flags.

Q: What is enum.unique used for?

A: It is a decorator that ensures no two enum members have the same value. Without it, duplicate values create aliases to the first member with that value.

Q: What is the enum.nonmember() function added in Python 3.11?

A: It wraps a value to explicitly exclude it from being an enum member: x = nonmember(42). Similarly, member() forces inclusion.

Q: What module lets you pack and unpack binary data in C struct format?

A: The struct module. It uses format strings like '<I' (little-endian unsigned int) to pack/unpack bytes.

Q: What does struct.pack('>I', 1024) return?

A: It returns b'\x00\x00\x04\x00' — the integer 1024 packed as a big-endian unsigned 32-bit integer.

Q: What module provides memory-mapped file access?

A: The mmap module. It maps a file into memory, allowing file I/O via memory operations, which can be significantly faster for large files.

Q: What is the shelve module used for?

A: It provides a persistent dictionary-like object backed by a database file (using dbm). Keys must be strings, but values can be any picklable Python object.

Q: Why is unpickling data from untrusted sources a security risk?

A: Because pickle.loads() can execute arbitrary code during deserialization. A malicious pickle payload can use the __reduce__ method to run arbitrary commands.

Q: How can you restrict what classes can be unpickled for security?

A: By subclassing pickle.Unpickler and overriding the find_class() method to whitelist allowed modules and classes.

Q: What safer alternatives to pickle exist for data serialization?

A: JSON (for simple data), msgpack, Protocol Buffers, or marshal (limited to Python-internal types). For untrusted data, JSON is strongly preferred.

Q: What is the pickle protocol version?

A: Pickle has protocol versions 0-5. Higher versions are more efficient. Protocol 5 (Python 3.8) added out-of-band data support for large buffers.

Q: What is marshal and how does it differ from pickle?

A: marshal is used internally by Python to read/write .pyc files. It is faster than pickle but only supports basic Python types, is not meant for general serialization, and its format can change between Python versions.

Q: What module provides functions for working with temporary files and directories?

A: The tempfile module, with NamedTemporaryFile, TemporaryDirectory, mkstemp(), and mkdtemp().

Q: What does the secrets module provide that random does not?

A: Cryptographically secure random numbers suitable for passwords, tokens, and security-sensitive operations. The random module uses a Mersenne Twister PRNG that is predictable and not suitable for security.

Q: What standard library module provides an interface to the operating system's random number generator?

A: os.urandom() provides raw random bytes. The secrets module (added in Python 3.6) wraps this in a more convenient API.

Q: What is the secrets.token_urlsafe(nbytes) function?

A: It generates a random URL-safe text string. With nbytes=32, it generates approximately 43 characters. Used for generating secure tokens.

Q: What does sys.getsizeof() return?

A: The size of an object in bytes, including the garbage collector overhead but not the size of objects it references (it is shallow, not deep).

Q: What is the weakref module used for?

A: It creates weak references to objects that don't prevent garbage collection. Useful for caches and observer patterns where you don't want to keep objects alive.

Q: What standard library module can you use to measure execution time of small code snippets?

A: The timeit module, which runs code multiple times and reports the execution time, disabling the garbage collector during timing by default.

Q: What does copy.deepcopy() do differently from copy.copy()?

A: copy() creates a shallow copy (new container but same references to contained objects). deepcopy() recursively copies all contained objects, creating fully independent copies.

Q: What standard library module provides support for generating universally unique identifiers?

A: The uuid module, supporting UUID versions 1, 3, 4, and 5.

Q: What is the pathlib module and when was it introduced?

A: Introduced in Python 3.4, pathlib provides object-oriented filesystem paths via the Path class, offering a more Pythonic alternative to os.path.

Q: What does the statistics module provide?

A: Basic statistical functions: mean(), median(), mode(), stdev(), variance(), quantiles(), and more. Added in Python 3.4.

Q: What is statistics.NormalDist used for?

A: Added in Python 3.8, it represents a normal (Gaussian) distribution and provides methods for CDF, PDF, quantiles, overlap with other distributions, and more.

Q: What does os.scandir() return and why is it preferred over os.listdir()?

A: It returns an iterator of DirEntry objects that include file metadata (type, stat info) cached from the directory scan. This avoids extra system calls, making it faster than listdir() followed by os.stat().

Q: What is shutil.copytree() used for?

A: Recursively copying an entire directory tree. It supports ignore patterns and dirs_exist_ok (Python 3.8+) to copy into an existing directory.

Q: What does json.dumps(obj, default=str) do?

A: It serializes obj to JSON, using str() as a fallback for objects that are not JSON-serializable. This is a common trick for handling datetime objects.

Q: What is inspect.signature() used for?

A: It returns a Signature object describing the parameters of a callable, including their names, default values, annotations, and kinds.

Q: What does dis.dis() do?

A: It disassembles Python bytecode, showing the low-level instructions that CPython executes. Useful for understanding performance and how Python compiles your code.

Q: What is the ast module used for?

A: It parses Python source code into an Abstract Syntax Tree (AST), which can be inspected, modified, and compiled. Used by linters, code formatters, and metaprogramming tools.

Q: What is importlib used for?

A: Programmatic control of Python's import system — importing modules by name string, reloading modules, finding loaders, and customizing import behavior.

Q: What is the logging module's hierarchy?

A: Loggers form a hierarchy based on dot-separated names (e.g., app.database is a child of app). Messages propagate up to parent loggers. The root logger is the ancestor of all loggers.

Q: What are the standard logging levels in Python, from lowest to highest?

A: DEBUG (10), INFO (20), WARNING (30), ERROR (40), CRITICAL (50). The default level is WARNING.

Q: What is pdb and how do you invoke it?

A: The Python debugger. Invoke it with python -m pdb script.py, or insert breakpoint() (Python 3.7+) or import pdb; pdb.set_trace() in code.

Q: What did breakpoint() (Python 3.7) replace?

A: The verbose import pdb; pdb.set_trace(). The breakpoint() built-in is also configurable via the PYTHONBREAKPOINT environment variable to use different debuggers.

Q: What is the graphlib module?

A: Added in Python 3.9, it provides TopologicalSorter for topological sorting of directed acyclic graphs. Useful for dependency resolution.

Q: What does math.prod() do, and when was it added?

A: Added in Python 3.8, it computes the product of all elements in an iterable: math.prod([1, 2, 3, 4]) returns 24. It is the multiplication equivalent of sum().

Q: What is the reprlib module used for?

A: It provides a version of repr() that limits output length for large or recursive data structures. reprlib.repr([1]*1000) gives a truncated representation.

Q: What is atexit used for?

A: Registering cleanup functions to be called when the interpreter exits normally. atexit.register(func) ensures func is called at shutdown.

Q: What does the traceback module provide?

A: Functions for extracting, formatting, and printing stack traces. Useful for logging exceptions without re-raising them.

Q: What does sys.intern(string) do?

A: It interns the string, ensuring only one copy exists in memory. Subsequent equal strings will be the same object, enabling is comparisons instead of == for performance.

Q: What is the site module responsible for?

A: It is automatically imported during Python startup and adds site-specific paths (like site-packages) to sys.path.

Q: What are .pth files?

A: Path configuration files in site-packages that contain paths to add to sys.path at startup.

Q: What is the PYTHONDONTWRITEBYTECODE environment variable?

A: When set, it prevents Python from creating __pycache__ directories and .pyc files. Equivalent to the -B flag.

Q: What does the gc module do?

A: It provides an interface to Python's garbage collector. You can trigger collection with gc.collect(), get referrers with gc.get_referrers(), and tune collection thresholds.

Q: What does sys.getrecursionlimit() return?

A: The current recursion limit. The default is 1000 on most platforms.

Q: What is the http.server module used for?

A: A simple HTTP server: python -m http.server 8000 serves the current directory. It is intended for development only, not production.

Q: What does python -m json.tool do?

A: It reads JSON from stdin and pretty-prints it. Useful as a command-line JSON formatter.

Q: What is python -m zipapp used for?

A: It creates executable Python ZIP applications (.pyz files). A ZIP file with a __main__.py entry point can be executed directly by Python.

Q: What does python -m calendar do?

A: It prints a calendar for the current year (or a specified year/month) to the terminal.

Q: What is the difference between a "naive" and "aware" datetime in Python?

A: A naive datetime has no timezone information (tzinfo is None). An aware datetime has timezone info attached. Comparing naive and aware datetimes raises a TypeError.

Q: Why should you avoid using datetime.utcnow()?

A: It returns a naive datetime (no timezone info) representing UTC time, which can be confused with local time. Use datetime.now(timezone.utc) instead. utcnow() was deprecated in Python 3.12.

Q: What is the zoneinfo module?

A: Added in Python 3.9, it provides IANA timezone support: ZoneInfo('America/New_York'). It replaced the need for the third-party pytz library.

Q: Why was pytz problematic?

A: pytz had a non-standard API — you had to use localize() instead of replace() to attach timezones. Using replace() with pytz gave wrong results for DST transitions. zoneinfo uses the standard datetime API.

Q: What is the epoch in Python's time module?

A: January 1, 1970, 00:00:00 UTC on most systems. time.time() returns seconds since the epoch.

Q: What does timedelta represent?

A: A duration — the difference between two dates or datetimes. It stores days, seconds, and microseconds internally.

Q: What is the maximum date Python's datetime can represent?

A: datetime.datetime.max is 9999-12-31 23:59:59.999999.

Q: What does datetime.datetime.fromisoformat() parse?

A: ISO 8601 formatted strings. In Python 3.11, it was expanded to handle many more ISO 8601 formats including the Z suffix for UTC.

Q: What module was added in Python 3.11 for parsing TOML files?

A: tomllib — a read-only TOML parser in the standard library. For writing TOML, you still need a third-party library like tomli-w.


9. String Formatting & Text

Q: What are the three string formatting approaches in Python?

A: %-formatting ('%s' % val), str.format() ('{}'.format(val)), and f-strings (f'{val}'). F-strings (Python 3.6+) are generally preferred for readability and performance.

Q: What does f'{value=}' do, introduced in Python 3.8?

A: The = specifier in f-strings shows both the expression text and its value. For example, x=42; f'{x=}' produces "x=42". It is useful for debugging.

Q: Can f-strings contain the backslash character?

A: Before Python 3.12, f-string expressions could not contain backslashes. In Python 3.12+, this restriction was lifted and backslashes are allowed in f-string expressions.

Q: What is string.Template and when would you use it?

A: string.Template uses $-based substitution ($name or ${name}). It is simpler and safer for user-provided templates because it doesn't allow arbitrary expression evaluation.

Q: What does textwrap.dedent() do?

A: It removes common leading whitespace from all lines in a multi-line string, useful for writing indented string literals that should not have leading whitespace in the output.

Q: What does textwrap.fill() do?

A: It wraps a single paragraph of text to a given width and returns a single string with newlines inserted. textwrap.wrap() returns a list of lines instead.

Q: What does the str.partition(sep) method return?

A: A 3-tuple: (before, sep, after). If the separator is not found, it returns (string, '', ''). There is also rpartition() which splits at the last occurrence.

Q: What is the difference between str.join() and concatenation with +?

A: str.join() is O(n) — it preallocates memory for the final string. Repeated + concatenation is O(n^2) because each concatenation creates a new string. Always prefer join() for combining many strings.

Q: What does str.removeprefix() do, and when was it added?

A: Added in Python 3.9, it removes the specified prefix if the string starts with it, otherwise returns the string unchanged. Similarly removesuffix() for suffixes.

Q: What is the difference between str.strip() and str.removeprefix()/str.removesuffix()?

A: strip() removes individual characters from both ends. removeprefix()/removesuffix() removes a specific substring. 'Arthur'.lstrip('Art') gives 'hur' (strips characters), while 'Arthur'.removeprefix('Art') gives 'hur' (removes exact prefix).

Q: What does the % operator do with strings in Python?

A: It performs old-style C-like string formatting: 'Hello %s, you are %d' % ('Alice', 30).

Q: What format spec would you use in an f-string to display a float with exactly 2 decimal places?

A: f'{value:.2f}'. The .2f means 2 decimal places with fixed-point notation.

Q: How do you format a number with thousands separators in an f-string?

A: f'{1000000:,}' produces '1,000,000'. You can also use _ as a separator: f'{1000000:_}' gives '1_000_000'.

Q: What does str.zfill(width) do?

A: It pads the string with leading zeros to the specified width. It handles a leading sign correctly: '-42'.zfill(5) gives '-0042'.

Q: What does str.casefold() do differently from str.lower()?

A: casefold() is more aggressive for case-insensitive comparisons. For example, the German 'SS'.casefold() gives 'ss', which correctly matches the lowercase form of 'ß'.

Q: What does str.translate() do?

A: It maps characters using a translation table created by str.maketrans(). It is the fastest way to replace or delete multiple characters at once.

Q: Why do we use raw strings (r'...') for regex patterns in Python?

A: Raw strings prevent Python from interpreting backslash sequences before the regex engine sees them. Without r, \b would be a backspace character rather than a word boundary.

Q: What is the difference between re.match() and re.search()?

A: re.match() only matches at the beginning of the string. re.search() scans through the entire string for the first match anywhere.

Q: What is the difference between re.search() and re.fullmatch()?

A: re.search() finds a match anywhere in the string. re.fullmatch() (added in Python 3.4) requires the entire string to match the pattern.

Q: What does re.compile() return and why use it?

A: It returns a compiled regular expression pattern object. Compiling is useful when you reuse the same pattern many times. Python caches recently used patterns internally.

Q: What do parentheses () do in a regex pattern?

A: They create capturing groups. Matched text can be retrieved via group(n) on the match object.

Q: What is a non-capturing group in regex?

A: (?:...) groups the pattern for alternation or quantification but does not capture the matched text. It is more efficient when you don't need the captured group.

Q: What is a positive lookahead in regex?

A: (?=...) asserts that what follows matches the pattern, without consuming any characters. For example, foo(?=bar) matches foo only if followed by bar.

Q: What is a negative lookahead?

A: (?!...) asserts that what follows does NOT match the pattern. For example, foo(?!bar) matches foo only if NOT followed by bar.

Q: What is a positive lookbehind?

A: (?<=...) asserts that what precedes the current position matches the pattern.

Q: What is a negative lookbehind?

A: (?<!...) asserts that what precedes does NOT match. For example, (?<!un)happy matches happy but not unhappy.

Q: What limitation do lookbehinds have in Python's re module?

A: Lookbehinds must be fixed-width — they cannot contain quantifiers like *, +, or {m,n} (variable-length). The regex third-party module removes this limitation.

Q: What does the re.IGNORECASE (or re.I) flag do?

A: It makes the pattern case-insensitive, matching both uppercase and lowercase letters.

Q: What does the re.MULTILINE (or re.M) flag do?

A: It makes ^ and $ match the start and end of each line (after/before a newline), not just the start and end of the entire string.

Q: What does the re.DOTALL (or re.S) flag do?

A: It makes the . metacharacter match any character including newlines. Without it, . matches everything except \n.

Q: What does the re.VERBOSE (or re.X) flag do?

A: It allows you to write multi-line regexes with comments and whitespace for readability. Unescaped whitespace and # comments are ignored in the pattern.

Q: What does re.findall() return when the pattern contains groups?

A: It returns a list of the groups (or tuples of groups if multiple groups exist), not the full matches. If there are no groups, it returns the full matches.

Q: What does re.sub(pattern, repl, string) do?

A: It replaces all occurrences of the pattern in the string with repl. repl can be a string (with backreferences like \1) or a callable that receives the match object.

Q: What does re.split(pattern, string) do differently from str.split()?

A: re.split() splits on a regex pattern. If the pattern contains capturing groups, the matched separators are included in the result list.

Q: What are named groups in regex and how do you use them?

A: (?P<name>...) creates a named group accessible via match.group('name') or match.groupdict(). Backreferences use (?P=name).

Q: What does re.escape(string) do?

A: It escapes all non-alphanumeric characters in the string, making it safe to use as a literal pattern in a regex.

Q: What does re.subn() return differently from re.sub()?

A: re.subn() returns a tuple (new_string, number_of_substitutions_made), while re.sub() returns just the new string.

Q: What is a named group backreference in regex?

A: (?P=name) in the pattern references a previously captured named group. For example, (?P<word>\w+)\s+(?P=word) matches repeated words.


10. Numeric Types

Q: Is there a limit to integer size in Python 3?

A: No. Python 3 integers have arbitrary precision — they can be as large as your memory allows. There is no overflow.

Q: What happened to long in Python 3?

A: Python 2 had both int (fixed-size) and long (arbitrary precision). Python 3 unified them into a single int type with arbitrary precision.

Q: What does float('inf') represent?

A: Positive infinity, per IEEE 754. It is greater than any other number. float('-inf') is negative infinity. float('nan') is Not a Number.

Q: What is the surprising result of float('nan') == float('nan')?

A: False. NaN is not equal to anything, including itself. This is per the IEEE 754 standard. To check for NaN, use math.isnan().

Q: Why does 0.1 + 0.2 != 0.3 in Python?

A: Because floating-point numbers use IEEE 754 binary representation, and 0.1 and 0.2 cannot be represented exactly in binary. The result is 0.30000000000000004. Use math.isclose() or decimal.Decimal.

Q: What is the output of print(0.1 + 0.2)?

A: 0.30000000000000004 due to IEEE 754 floating-point representation.

Q: What module provides arbitrary-precision decimal arithmetic?

A: The decimal module with its Decimal class. It avoids the floating-point representation issues of float.

Q: How do you set the precision for decimal.Decimal operations?

A: Via decimal.getcontext().prec = n. The default precision is 28 significant digits.

Q: What module allows exact arithmetic with fractions?

A: The fractions module with its Fraction class. For example, Fraction(1, 3) + Fraction(1, 6) gives Fraction(1, 2).

Q: Does Python have native support for complex numbers?

A: Yes. Use j or J for the imaginary part: z = 3 + 4j. Access parts with z.real and z.imag. The cmath module provides math functions for complex numbers.

Q: What does divmod(a, b) return?

A: A tuple (a // b, a % b) — the quotient and remainder. It is more efficient than computing them separately.

Q: What is math.isclose(a, b) used for?

A: Comparing floating-point numbers for approximate equality, with configurable relative tolerance (rel_tol, default 1e-9) and absolute tolerance (abs_tol, default 0.0).

Q: What does int.bit_length() return?

A: The number of bits needed to represent the integer (excluding sign and leading zeros). For example, (255).bit_length() returns 8.

Q: What does int.to_bytes() do?

A: Converts an integer to a bytes representation. For example, (1024).to_bytes(2, byteorder='big') returns b'\x04\x00'.

Q: What is math.inf equal to?

A: float('inf'). It represents positive infinity.

Q: What does int.from_bytes() do?

A: Creates an integer from a bytes object: int.from_bytes(b'\x04\x00', byteorder='big') returns 1024.

Q: What is the numbers module?

A: It defines abstract base classes for numeric types: Number, Complex, Real, Rational, Integral. It forms a numeric tower for type checking.


11. Memory Management & Internals

Q: What is reference counting in CPython?

A: The primary memory management mechanism. Each object tracks how many references point to it. When the count reaches zero, the memory is freed immediately. The cyclic garbage collector handles reference cycles.

Q: What is the GIL?

A: The Global Interpreter Lock — a mutex in CPython that allows only one thread to execute Python bytecode at a time. It simplifies memory management but prevents true multi-threaded parallelism for CPU-bound code.

Q: Why does the GIL exist?

A: To protect CPython's reference counting from race conditions. Without the GIL, every reference count update would need its own lock, adding significant overhead.

Q: What is CPython bytecode?

A: The intermediate representation that Python source code is compiled to before execution. Each .py file is compiled to bytecode (stored in .pyc files) which the CPython virtual machine interprets.

Q: What is the __pycache__ directory?

A: A directory Python creates to store compiled bytecode (.pyc files). It avoids recompiling modules that haven't changed. The files are named with the Python version, like module.cpython-312.pyc.

Q: What does python -O do?

A: Runs Python with basic optimizations: removes assert statements and sets __debug__ to False. -OO also removes docstrings.

Q: What is the __debug__ built-in constant?

A: It is True under normal execution and False when Python runs with the -O flag. assert statements are only executed when __debug__ is True.

Q: What is the small integer cache in CPython?

A: CPython pre-allocates integers from -5 to 256 as singleton objects. Any code that creates an integer in this range gets a reference to the same object, saving memory and time.

Q: What is string interning?

A: A technique where identical strings share the same object in memory. CPython automatically interns strings that look like identifiers. You can manually intern with sys.intern().

Q: How does CPython's garbage collector handle circular references?

A: It uses a generational garbage collector with three generations. Objects that survive collection are promoted to older generations, which are collected less frequently. It detects unreachable cycles by tracking container objects.

Q: What are the three generations in CPython's garbage collector?

A: Generation 0 (youngest, collected most frequently), generation 1 (middle), and generation 2 (oldest, collected least frequently). New objects start in generation 0.

Q: What is the peephole optimizer in CPython?

A: A bytecode optimizer that performs simple optimizations like constant folding (1 + 2 becomes 3), dead code elimination, and converting operations to more efficient forms.

Q: What is sys.maxsize?

A: The largest positive integer supported by the platform's Py_ssize_t type (typically 2^63 - 1 on 64-bit). It is NOT the maximum integer Python can handle, but is the maximum size for containers.

Q: What does sys.version_info return?

A: A named tuple with major, minor, micro, releaselevel, and serial fields.

Q: What does sys.platform return on Linux, macOS, and Windows?

A: 'linux', 'darwin', and 'win32' respectively.


12. Concurrency & Async

Q: What is the difference between concurrency and parallelism in Python?

A: Concurrency (doing multiple things by switching between them) is achieved with asyncio or threading. Parallelism (doing multiple things simultaneously) requires multiprocessing due to the GIL.

Q: What is async/await in Python?

A: Syntax for asynchronous programming introduced in Python 3.5 (PEP 492). async def defines a coroutine, and await suspends execution until an awaitable completes.

Q: What is asyncio.run() used for?

A: It is the main entry point for running async code from synchronous code. It creates an event loop, runs the coroutine, and closes the loop. Added in Python 3.7.

Q: What is multiprocessing.Pool used for?

A: It creates a pool of worker processes for parallel execution, with methods like map(), apply_async(), and starmap() to distribute work across CPU cores.

Q: What is concurrent.futures and when was it introduced?

A: Added in Python 3.2, it provides a high-level interface for asynchronous execution using ThreadPoolExecutor and ProcessPoolExecutor, both implementing a unified Future pattern.

Q: What is the TaskGroup in Python 3.11's asyncio?

A: asyncio.TaskGroup provides structured concurrency — a context manager that runs multiple tasks and ensures all are completed (or cancelled) before exiting the block.

Q: What is the difference between asyncio.gather() and TaskGroup?

A: gather() runs coroutines concurrently but has error-handling issues — if one task fails, others may be left running. TaskGroup (3.11) provides structured concurrency: if any task fails, all others are cancelled and the group raises an ExceptionGroup.

Q: What are context variables (contextvars)?

A: Introduced in Python 3.7, the contextvars module provides context-local variables similar to thread-local storage but works correctly with asyncio tasks. Used for things like request-scoped state.

Q: What is the GIL's impact on I/O-bound vs CPU-bound threading?

A: I/O-bound threading works well because the GIL is released during I/O operations (network, file). CPU-bound threading is ineffective because only one thread can execute Python bytecode at a time.

Q: What is threading.Lock used for?

A: A primitive lock for mutual exclusion. Only one thread can hold the lock at a time. Use with lock: for safe acquisition and release.

Q: What is a daemon thread?

A: A thread that runs in the background and is automatically killed when all non-daemon threads exit. Set with thread.daemon = True before starting.

Q: What is asyncio.Queue?

A: An async-safe queue for producer-consumer patterns in asyncio code. Unlike queue.Queue (for threads), it uses await for get() and put().

Q: What is asyncio.Semaphore used for?

A: Limiting the number of concurrent coroutines accessing a shared resource — for example, limiting concurrent HTTP connections to avoid overwhelming a server.


13. Type System & Type Hints

Q: What PEP introduced type hints to Python?

A: PEP 484, accepted in Python 3.5. It introduced the typing module.

Q: What does typing.Protocol do?

A: Introduced in Python 3.8 (PEP 544), it enables structural subtyping (duck typing for type checkers). A class satisfies a Protocol if it has the required methods/attributes, without explicitly inheriting from it.

Q: What is TypeVar used for?

A: Defining generic type variables. For example, T = TypeVar('T') allows writing def first(items: list[T]) -> T to indicate the return type matches the list element type.

Q: What is ParamSpec used for?

A: Introduced in Python 3.10 (PEP 612), it captures the parameter types of a callable, enabling accurate typing of decorators that preserve the wrapped function's signature.

Q: What is TypeAlias used for?

A: Explicitly declaring a type alias: Vector: TypeAlias = list[float]. Added in Python 3.10. In Python 3.12, the type statement replaced it.

Q: What is the type statement in Python 3.12?

A: A new syntax for defining type aliases: type Vector = list[float]. It is lazily evaluated and supports generic type parameters inline.

Q: What new generic syntax was introduced in Python 3.12?

A: PEP 695 introduced def func[T](x: T) -> T: and class MyClass[T]: syntax, replacing the verbose TypeVar pattern with inline generic parameters.

Q: What is typing.Literal used for?

A: Introduced in Python 3.8, it restricts values to specific literal values: def set_mode(mode: Literal['r', 'w', 'a']) -> None.

Q: What is typing.TypeGuard used for?

A: Added in Python 3.10, it narrows types in conditional branches. A function returning TypeGuard[X] tells the type checker that if the function returns True, the argument is of type X.

Q: What is typing.TypedDict used for?

A: Defining the expected structure of a dictionary with specific keys and their types: class Movie(TypedDict): title: str; year: int. Added in Python 3.8.

Q: What is typing.overload used for?

A: Declaring multiple type signatures for a single function, allowing type checkers to determine the return type based on the argument types. The decorated stubs are for type checking only.

Q: What is typing.Final used for?

A: Declaring that a variable should not be reassigned: MAX_SIZE: Final = 100. A type checker will flag any subsequent reassignment.

Q: What is typing.Never (Python 3.11) or typing.NoReturn used for?

A: NoReturn annotates functions that never return (they always raise an exception or run forever). Never (Python 3.11) is the bottom type — it also works for variables that should never have a value.

Q: Can you use built-in types as generics since Python 3.9?

A: Yes. PEP 585 (Python 3.9) allows list[int], dict[str, int], tuple[int, ...] directly, making typing.List, typing.Dict, etc. redundant.

Q: What is typing.Annotated used for?

A: Added in Python 3.9 (PEP 593), it attaches arbitrary metadata to type hints: Annotated[int, ValueRange(0, 100)]. Libraries like Pydantic and FastAPI use this for validation.

Q: What is the typing.Self type, and when was it introduced?

A: Added in Python 3.11 (PEP 673), Self is used in method return annotations to indicate the method returns an instance of the enclosing class.

Q: What does typing.Unpack do?

A: Added in Python 3.11, it is used for typing variadic generics with TypeVarTuple, enabling typed variable-length tuple types and **kwargs typing.

Q: What is typing.runtime_checkable used for?

A: It is a decorator for Protocol classes that allows isinstance() checks at runtime.

Q: What does the __future__ module's annotations import do?

A: from __future__ import annotations makes all annotations lazily evaluated — they are stored as strings instead of being evaluated at definition time (PEP 563).

Q: What is PEP 649 about?

A: "Deferred Evaluation of Annotations" — an alternative to PEP 563 that evaluates annotations lazily on access rather than converting them to strings. Accepted for Python 3.14.


14. Python Packaging & Ecosystem

Q: What does PyPI stand for?

A: Python Package Index — the official repository for third-party Python packages, hosted at pypi.org.

Q: Approximately how many packages are on PyPI as of 2025?

A: Over 500,000 packages.

Q: What are historically the most downloaded packages on PyPI?

A: boto3, urllib3, botocore, requests, setuptools, certifi, charset-normalizer, idna, pip, and python-dateutil are consistently among the top.

Q: What was the original name of pip?

A: pip is a recursive acronym: "pip installs packages" (originally "pip installs Python"). It replaced easy_install from setuptools.

Q: When was pip first released?

A: In 2008, created by Ian Bicking.

Q: What tool is the modern standard for building Python packages?

A: build (as in python -m build), using a pyproject.toml configuration. setuptools remains the most common build backend.

Q: What file replaced setup.py and setup.cfg as the modern Python project configuration standard?

A: pyproject.toml, standardized by PEP 518 (build system requirements) and PEP 621 (project metadata).

Q: What is virtualenv and why is it important?

A: It creates isolated Python environments with their own packages, preventing dependency conflicts between projects.

Q: What is the difference between venv and virtualenv?

A: venv is in the standard library but has fewer features. virtualenv is faster, supports more Python versions, has more configuration options, and can create environments for different interpreters.

Q: What is conda and how does it differ from pip?

A: conda is a cross-platform package and environment manager that handles non-Python dependencies (C libraries, etc.). pip only manages Python packages.

Q: What is uv in the Python ecosystem?

A: uv is an extremely fast Python package installer and resolver written in Rust by Astral (the makers of Ruff). It is a drop-in replacement for pip and pip-tools, often 10-100x faster.

Q: What is ruff?

A: An extremely fast Python linter and code formatter written in Rust, created by Charlie Marsh / Astral. It aims to replace Flake8, isort, pyupgrade, and Black in a single tool.

Q: What is the wheel format?

A: A built distribution format (.whl files) introduced by PEP 427. Wheels are pre-built and install faster than source distributions because they don't require a build step.

Q: What is Black?

A: An opinionated Python code formatter that enforces a consistent style with minimal configuration. Its motto is "the uncompromising code formatter."

Q: What is a PEP 517 build backend?

A: A system that builds Python packages according to the standard defined in PEP 517. Examples include setuptools, flit-core, hatchling, and maturin.

Q: What is pyenv?

A: A tool for managing multiple Python versions on the same machine. It lets you install and switch between different Python versions per-project or globally.

Q: What is pipx?

A: A tool for installing Python CLI applications in isolated environments. Each application gets its own virtualenv, preventing dependency conflicts between tools.

Q: What is poetry?

A: A Python dependency management and packaging tool that uses pyproject.toml, provides deterministic builds via a lock file, and manages virtual environments.

Q: What is hatch?

A: A modern Python project manager and build backend. It manages environments, builds packages, publishes to PyPI, and runs scripts.

Q: What is maturin?

A: A build tool for Rust-based Python extensions (PyO3/cffi). It compiles Rust code into Python-installable wheels.

Q: What is isort?

A: A tool that automatically sorts Python imports alphabetically and separates them into sections (stdlib, third-party, local). Now largely superseded by ruff.

Q: What is pre-commit?

A: A framework for managing and running git pre-commit hooks. It can run linters, formatters, and other checks automatically before each commit.


15. Testing

Q: What is pytest's key advantage over unittest?

A: Simpler syntax — tests are plain functions with assert statements instead of requiring classes and self.assertEqual() methods. It also has a powerful fixture system and plugin ecosystem.

Q: What does pytest.fixture do?

A: It defines reusable test setup/teardown functions that are injected into test functions by name. Fixtures can have different scopes (function, class, module, session).

Q: What is pytest.mark.parametrize used for?

A: Running the same test with multiple sets of inputs: @pytest.mark.parametrize("input,expected", [(1,2), (3,4)]) runs the test twice with different arguments.

Q: What is Hypothesis?

A: A property-based testing library for Python (inspired by Haskell's QuickCheck). It generates random test inputs based on strategies and finds edge cases automatically.

Q: What is tox?

A: A tool for automating testing across multiple Python versions and environments. It creates virtualenvs and runs test commands in each.

Q: What is nox?

A: Similar to tox but uses Python scripts instead of INI configuration files for defining test sessions. Created by Thea Flowers.

Q: What is unittest.mock.patch used for?

A: Temporarily replacing an object with a mock during testing. It can be used as a decorator or context manager: @patch('module.ClassName').

Q: What is unittest.mock.MagicMock?

A: A mock object that implements most magic methods automatically. It records calls and allows you to set return values and assert how it was used.

Q: What is doctest?

A: A module that tests code examples embedded in docstrings by running them and comparing output. It serves double duty as documentation and tests.

Q: What is coverage.py used for?

A: Measuring code coverage — what percentage of your code is executed during testing. It can report line coverage, branch coverage, and generate HTML reports.

Q: What are pytest marks?

A: Decorators that categorize tests: @pytest.mark.slow, @pytest.mark.skip, @pytest.mark.xfail. Custom marks allow running subsets of tests with -m.

Q: What is conftest.py in pytest?

A: A special file where you define fixtures, hooks, and plugins that are automatically available to all tests in the same directory and subdirectories. No import needed.

Q: What is pytest's tmp_path fixture?

A: A built-in fixture that provides a temporary directory unique to each test invocation. It returns a pathlib.Path object.

Q: What is pytest.raises?

A: A context manager that asserts an exception is raised: with pytest.raises(ValueError):. It also allows inspecting the exception via excinfo.value.


16. Web Frameworks

Q: What is Django's primary design philosophy?

A: "The web framework for perfectionists with deadlines." It follows the "batteries included" philosophy with an ORM, admin interface, authentication, templating, and more built-in.

Q: What design pattern does Django follow?

A: Model-Template-View (MTV), which is Django's variation of MVC. Models define data, Templates handle presentation, and Views contain business logic.

Q: What is Django's ORM?

A: An Object-Relational Mapper that lets you define database models as Python classes and query databases using Python code instead of raw SQL.

Q: When was Django first released?

A: July 2005. It was originally developed at the Lawrence Journal-World newspaper in Lawrence, Kansas.

Q: Who created Django?

A: Adrian Holovaty and Simon Willison at the Lawrence Journal-World, a newspaper in Lawrence, Kansas.

Q: What does Flask call itself?

A: A "micro" web framework. It provides the core (routing, request/response handling, templating via Jinja2) but leaves choices like ORM and authentication to extensions.

Q: Who created Flask?

A: Armin Ronacher, as part of the Pallets project. It was originally an April Fools' joke in 2010 that became wildly popular.

Q: What WSGI toolkit does Flask use under the hood?

A: Werkzeug (German for "tool") for WSGI utilities and request/response handling.

Q: What is FastAPI's key distinguishing feature?

A: Automatic API documentation (Swagger UI and ReDoc) generated from Python type hints, along with automatic request validation using Pydantic models.

Q: What ASGI server is commonly used with FastAPI?

A: Uvicorn, which is based on uvloop and httptools for high performance.

Q: What is the difference between WSGI and ASGI?

A: WSGI (Web Server Gateway Interface) is synchronous — one request per thread. ASGI (Asynchronous Server Gateway Interface) supports async, WebSockets, and long-lived connections.

Q: What framework is FastAPI built on top of?

A: Starlette (for the web parts) and Pydantic (for data validation).

Q: What is Tornado known for?

A: Being one of the first Python async web frameworks (originally from FriendFeed/Facebook, released 2009). It has its own event loop and is designed for long-polling and WebSockets.

Q: What is Bottle's claim to fame?

A: It is a single-file micro web framework with no dependencies outside the standard library — the entire framework is one Python file.

Q: What is AIOHTTP?

A: An async HTTP client/server framework built on asyncio. It serves as both a web server framework and an HTTP client library.

Q: What is Sanic?

A: An async Python web framework designed for speed, similar to Flask's API but fully async.

Q: What is Litestar (formerly Starlite)?

A: A high-performance ASGI framework with an emphasis on being opinionated, having built-in dependency injection, and supporting multiple serialization libraries beyond Pydantic.

Q: Who is the current fastest growing Python web framework (as of 2025)?

A: FastAPI, created by Sebastian Ramirez in 2018. It became one of the most starred Python frameworks on GitHub within a few years.

Q: What is Gunicorn?

A: A popular WSGI HTTP server for Unix. It uses a pre-fork worker model and is commonly deployed with Django or Flask behind Nginx.

Q: What is the Django admin?

A: An automatically generated web-based admin interface for managing data. It introspects your models and creates CRUD pages with minimal configuration.


17. Data Science Stack

Q: What does NumPy stand for?

A: Numerical Python.

Q: What is the core data structure in NumPy?

A: The ndarray (n-dimensional array), a fixed-size, homogeneous, contiguous block of memory that enables fast vectorized operations.

Q: Why are NumPy operations faster than Python loops?

A: NumPy operations are implemented in C and operate on contiguous memory arrays, avoiding Python's per-element type checking and interpreter overhead. This is called vectorization.

Q: What is broadcasting in NumPy?

A: A set of rules that allows NumPy to perform operations on arrays of different shapes by automatically expanding the smaller array.

Q: What is a Pandas DataFrame?

A: A 2D labeled data structure with columns of potentially different types, similar to a spreadsheet or SQL table.

Q: What is a Pandas Series?

A: A 1D labeled array — essentially a single column of a DataFrame. It can hold any data type.

Q: What does pandas.read_csv() do?

A: It reads a CSV file into a DataFrame. It has dozens of parameters for handling different delimiters, encodings, missing values, data types, and more.

Q: What is Matplotlib's pyplot interface?

A: A MATLAB-like procedural interface for creating plots, accessed as matplotlib.pyplot (commonly imported as plt).

Q: Who created Matplotlib and why?

A: John D. Hunter created it in 2003 to emulate MATLAB's plotting capabilities in Python, so he could do his epilepsy research without a MATLAB license.

Q: What is seaborn?

A: A statistical data visualization library built on top of Matplotlib that provides a higher-level interface for creating attractive statistical graphics.

Q: What does SciPy provide that NumPy does not?

A: Higher-level scientific computing algorithms: optimization, integration, interpolation, signal processing, linear algebra decompositions, sparse matrices, spatial data structures, and statistics.

Q: What is scikit-learn?

A: The most widely used Python machine learning library, providing consistent APIs for classification, regression, clustering, dimensionality reduction, model selection, and preprocessing.

Q: What API convention does scikit-learn follow?

A: The fit/predict/transform pattern: model.fit(X_train, y_train) trains, model.predict(X_test) predicts, and transformers use transform() or fit_transform().

Q: What is Jupyter's name derived from?

A: The three core programming languages it supports: Julia, Python, and R. It evolved from IPython Notebook.

Q: What Python library has become the standard for data validation and settings management?

A: Pydantic, which uses Python type annotations for runtime data validation, serialization, and deserialization.

Q: What is Polars?

A: A fast DataFrame library written in Rust with a Python interface. It is designed as a more performant alternative to Pandas, with lazy evaluation and better multi-threaded performance.

Q: What is the difference between Pandas and Polars?

A: Pandas uses NumPy arrays internally and runs single-threaded. Polars uses Apache Arrow memory format, supports lazy evaluation, and automatically parallelizes operations across CPU cores.


18. Python Easter Eggs & WAT Moments

Q: What happens when you run import this in Python?

A: It prints "The Zen of Python" — 19 aphorisms by Tim Peters that capture Python's design philosophy.

Q: Who wrote The Zen of Python?

A: Tim Peters, a major early contributor to Python and author of the Timsort algorithm.

Q: Why does import this have 19 aphorisms when The Zen of Python was supposed to have 20?

A: Tim Peters intentionally left the 20th aphorism blank for Guido to fill in — he never did.

Q: What is the Easter egg hidden in the source code of the this module?

A: The Zen text is stored as a ROT13-encoded string and decoded at import time. The module itself is a playful example of obfuscated code — contradicting the very principles it espouses.

Q: What are all 19 aphorisms of The Zen of Python?

A: 1. Beautiful is better than ugly. 2. Explicit is better than implicit. 3. Simple is better than complex. 4. Complex is better than complicated. 5. Flat is better than nested. 6. Sparse is better than dense. 7. Readability counts. 8. Special cases aren't special enough to break the rules. 9. Although practicality beats purity. 10. Errors should never pass silently. 11. Unless explicitly silenced. 12. In the face of ambiguity, refuse the temptation to guess. 13. There should be one -- and preferably only one -- obvious way to do it. 14. Although that way may not be obvious at first unless you're Dutch. 15. Now is better than never. 16. Although never is often better than right now. 17. If the implementation is hard to explain, it's a bad idea. 18. If the implementation is easy to explain, it may be a good idea. 19. Namespaces are one honking great idea -- let's do more of those!

Q: Which Zen aphorism is often cited to argue against Java-style getter/setter methods in Python?

A: "Simple is better than complex" and "There should be one -- and preferably only one -- obvious way to do it."

Q: Which Zen aphorism is the "Dutch" one a reference to?

A: "Although that way may not be obvious at first unless you're Dutch" — a reference to Guido van Rossum being Dutch.

Q: What is the significance of antigravity in Python?

A: import antigravity opens the classic XKCD comic #353 about Python in a web browser.

Q: What does import __hello__ do?

A: It prints "Hello world!".

Q: What happens if you type from __future__ import braces in Python?

A: You get SyntaxError: not a chance — a humorous rejection of curly-brace syntax.

Q: What happens when you multiply a list: [[]] * 3?

A: You get [[], [], []], but all three inner lists are the SAME object. Modifying one modifies all: a = [[]] * 3; a[0].append(1) gives [[1], [1], [1]].

Q: What is the output of round(0.5) and round(1.5) in Python 3?

A: round(0.5) gives 0 and round(1.5) gives 2. Python 3 uses "banker's rounding" (round half to even).

Q: What is the WAT moment with hash(-1) and hash(-2) in CPython?

A: hash(-1) == hash(-2) is True. CPython's hash function maps -1 to -2 internally because -1 is used as an error indicator in the C implementation.

Q: Why is True + True == 2?

A: Because bool is a subclass of int, True equals 1, so True + True evaluates to 1 + 1 = 2.

Q: What is the WAT moment with [] == False?

A: [] == False is False. An empty list is falsy (bool([]) is False), but == compares by value, and a list does not equal a boolean.

Q: What is the antigravity module's geohash feature?

A: antigravity.geohash(lat, lon, date) generates a random location using the XKCD geohashing algorithm (comic #426). It was added as a secondary Easter egg.

Q: What does import __phello__ do in Python 3.12+?

A: It prints "Hello world!" — a frozen "hello world" package added as part of the frozen module infrastructure.

Q: What is the WAT moment with tuple addition?

A: () + () gives (). But (1,) + (2,) gives (1, 2). The trailing comma is required for single-element tuples: (1) is just the integer 1, not a tuple.

Q: What is the surprising behavior of is with short strings?

A: Due to string interning, a = 'hello'; b = 'hello'; a is b is True. But a = 'hello world'; b = 'hello world'; a is b may be False because strings with spaces are not automatically interned.


19. Python for DevOps/SRE

Q: What is boto3?

A: The official AWS SDK for Python. It provides low-level client interfaces and higher-level resource interfaces for AWS services.

Q: What is the difference between boto3 client and resource interfaces?

A: Client provides a low-level, 1:1 mapping to AWS API operations. Resource provides a higher-level, object-oriented interface. Client is more complete; resource is more Pythonic.

Q: What is paramiko?

A: A Python library implementing SSHv2. It provides both client and server functionality for SSH connections, file transfers (SFTP), and remote command execution.

Q: What is Fabric?

A: A library for executing shell commands remotely over SSH. Built on top of paramiko and Invoke, it is commonly used for deployment automation.

Q: What is Invoke?

A: A task execution library — a Pythonic replacement for Make. It provides a clean API for running shell commands and organizing task functions.

Q: What is Click?

A: A Python package by the Pallets Project (same team as Flask) for creating command-line interfaces using decorators.

Q: What is Typer?

A: A CLI library by Sebastian Ramirez (FastAPI author) built on top of Click that uses Python type hints for argument parsing.

Q: What is Python Fire?

A: A Google library that automatically generates CLI interfaces from any Python object (function, class, module, dict).

Q: What is the standard library module for parsing command-line arguments?

A: argparse (since Python 3.2, replacing the older optparse).

Q: What does argparse.ArgumentParser.add_subparsers() do?

A: Creates subcommands (like git commit, git push), where each subcommand has its own set of arguments.

Q: What is Rich?

A: A Python library for rich text and formatting in the terminal. It provides syntax highlighting, tables, progress bars, tracebacks, markdown rendering, and more.

Q: What is httpx?

A: A modern HTTP client for Python that supports both sync and async requests, HTTP/2, and has an API similar to requests. It is the async-capable successor to requests.

Q: What is the requests library?

A: The most popular Python HTTP client library, known for its simple API: requests.get(url). Created by Kenneth Reitz.

Q: Why should you never use shell=True with subprocess when handling user input?

A: It enables shell injection attacks. User input could contain shell metacharacters that execute arbitrary commands. Always pass arguments as a list instead.

Q: What is the safer way to use subprocess?

A: Use subprocess.run(['cmd', 'arg1', 'arg2']) with a list of arguments instead of a shell string. This avoids shell injection vulnerabilities.

Q: What is Jinja2?

A: A template engine for Python used by Flask, Ansible, and many other tools. It supports template inheritance, macros, filters, and auto-escaping.

Q: What is the subprocess.run() function?

A: The recommended way to run external commands (Python 3.5+). It returns a CompletedProcess with returncode, stdout, and stderr. Use check=True to raise on non-zero exit codes.

Q: What is shlex.split() used for?

A: Splitting a shell command string into a list of arguments using shell-like syntax. Useful for converting "cmd --flag 'arg with spaces'" into ['cmd', '--flag', 'arg with spaces'].

Q: What is YAML handling in Python?

A: The pyyaml library is the standard. Use yaml.safe_load() (not yaml.load()) to avoid arbitrary code execution from untrusted YAML.

Q: What is ansible-runner?

A: A Python library that provides a programmatic interface for running Ansible playbooks, roles, and tasks from Python code.


20. Dunder Methods Catalog

Q: What is the difference between __str__ and __repr__?

A: __repr__ should return an unambiguous string representation (ideally valid Python to recreate the object). __str__ should return a readable, user-friendly string. __repr__ is used in the REPL; __str__ is used by print().

Q: What is __format__ used for?

A: It is called by format() and f-strings to customize how an object is formatted. For example, datetime objects use it to support format codes like f'{dt:%Y-%m-%d}'.

Q: What does __hash__ need to be consistent with?

A: __eq__. Objects that compare equal must have the same hash. If you define __eq__, Python sets __hash__ to None (making instances unhashable) unless you also define __hash__.

Q: What is __getattr__ vs __getattribute__?

A: __getattribute__ is called for every attribute access. __getattr__ is only called when normal attribute lookup fails. Overriding __getattribute__ is risky and can easily cause infinite recursion.

Q: What is __missing__ used for?

A: It is called by dict.__getitem__() when a key is not found. defaultdict uses this to generate default values. You can override it in dict subclasses.

Q: What is the __contains__ method?

A: It implements the in operator: x in obj calls obj.__contains__(x). If not defined, Python falls back to iterating through __iter__.

Q: What method makes an object callable?

A: __call__. If a class defines __call__, its instances can be called like functions: obj().

Q: What is __len__ used for?

A: It implements len(obj). It should return a non-negative integer. An object with __len__ is also considered falsy if __len__ returns 0 (unless __bool__ is defined).

Q: What is the __bool__ method?

A: It defines the truth value of an object. If not defined, Python falls back to __len__ (0 is falsy), then defaults to True.

Q: What is a context manager protocol?

A: Any object that implements __enter__ and __exit__ methods. __enter__ is called at the start of a with block, and __exit__ is called at the end.

Q: What arguments does __exit__ receive?

A: Three arguments: exc_type, exc_val, and exc_tb (exception type, value, and traceback). If no exception occurred, all are None. Returning True suppresses the exception.

Q: What is a __fspath__ method?

A: Added in Python 3.6, it allows objects to represent filesystem paths. os.fspath() calls it. pathlib.Path implements it.

Q: What is __del__ used for?

A: It is a finalizer called when an object is about to be garbage collected. It is unreliable for cleanup because you cannot predict when (or if) it will be called. Use context managers instead.

Q: What is __eq__ and __ne__?

A: __eq__ implements ==, __ne__ implements !=. By default, __ne__ delegates to __eq__ and negates the result.

Q: What are __lt__, __le__, __gt__, __ge__?

A: Rich comparison methods: less-than, less-or-equal, greater-than, greater-or-equal. They enable custom comparison logic and are used by sorted() and comparison operators.

Q: What is __add__ vs __radd__?

A: __add__ handles self + other. __radd__ (reflected add) handles other + self when the left operand's __add__ returns NotImplemented.

Q: What is __iadd__?

A: The in-place add method, called by +=. For mutable objects (like lists), it modifies in-place. For immutable objects (like tuples), it creates a new object.

Q: What is __getitem__ used for?

A: It implements obj[key]. For sequences, the key is an integer index. For mappings, it can be any hashable key. It also enables iteration as a fallback if __iter__ is not defined.

Q: What is __setitem__ and __delitem__?

A: __setitem__ implements obj[key] = value. __delitem__ implements del obj[key].

Q: What is __iter__ vs __getitem__ for iteration?

A: Python first tries __iter__ for iteration. If not defined, it falls back to calling __getitem__ with increasing integer indices starting from 0, stopping at IndexError.

Q: What is __class_getitem__ vs __getitem__?

A: __class_getitem__ handles MyClass[item] (class-level subscript, used for generics). __getitem__ handles instance[item] (instance-level subscript).

Q: What is __sizeof__ used for?

A: Returns the internal size of the object in bytes (used by sys.getsizeof()). It does not include the size of referenced objects.

Q: What is __slots__ effect on __dict__?

A: When __slots__ is defined, instances do not have a __dict__ attribute. This saves memory but means you cannot add arbitrary attributes to instances.


21. Version-Specific Features

Q: What major features were added in Python 3.8?

A: The walrus operator := (PEP 572), positional-only parameters / (PEP 570), f-string = for debugging, functools.cached_property, typing.Literal, typing.Protocol, math.prod(), and statistics.NormalDist.

Q: What major features were added in Python 3.9?

A: Dict merge operator | (PEP 584), str.removeprefix()/removesuffix(), zoneinfo module, built-in generic types (list[int] instead of typing.List[int]), graphlib.TopologicalSorter, and functools.cache.

Q: What major features were added in Python 3.10?

A: Structural pattern matching match/case (PEP 634), TypeGuard, ParamSpec, pairwise() in itertools, zip(strict=True), and better error messages.

Q: What major features were added in Python 3.11?

A: Exception groups and except*, asyncio.TaskGroup, tomllib, typing.Self, 10-60% speed improvement, much better error messages with precise locations, StrEnum, and typing.Never.

Q: What major features were added in Python 3.12?

A: F-string improvements (any expression allowed), type statement (PEP 695), per-interpreter GIL (PEP 684), sys.monitoring (PEP 669), itertools.batched(), Linux perf profiler support, and deprecated distutils removal.

Q: What major features were added in Python 3.13?

A: Free-threading experimental build (--disable-gil, PEP 703), new interactive REPL with multiline editing and color, PEP 649 deferred annotations (experimental), and an experimental JIT compiler.

Q: What is PEP 703 (free-threading)?

A: It removes the GIL as an experimental opt-in build option in Python 3.13. It enables true multi-threaded parallelism but requires significant changes to C extensions.

Q: What is the per-interpreter GIL in Python 3.12?

A: PEP 684 allows each sub-interpreter to have its own GIL, enabling true parallelism between interpreters without the complexity of free-threading.

Q: What is sys.monitoring in Python 3.12?

A: A new API for monitoring Python execution (PEP 669), designed for debuggers and profilers. It is much lower overhead than the previous sys.settrace approach.

Q: What performance improvement was made in Python 3.11?

A: CPython 3.11 is 10-60% faster than 3.10 thanks to the "Faster CPython" project (led by Mark Shannon, funded by Microsoft). Key optimizations include adaptive specialization of bytecode.

Q: What is the perf profiler support added in Python 3.12?

A: Python 3.12 added support for the Linux perf profiler, allowing Python function names to appear in perf output for system-level profiling.

Q: What major feature did Python 3.12 change regarding f-strings?

A: F-strings were completely reformulated with a new parser, removing many previous limitations. They can now contain any valid Python expression, including nested f-strings and backslashes.

Q: What new REPL was introduced in Python 3.13?

A: A new interactive REPL with multi-line editing, color support, and better paste handling, replacing the basic readline-based REPL.

Q: What is the match statement guard clause?

A: An if condition added to a case pattern: case [x, y] if x > 0: only matches if the pattern matches AND the guard condition is true.

Q: What PEPs define structural pattern matching?

A: PEP 634 (specification), PEP 635 (motivation and rationale), and PEP 636 (tutorial).

Q: Can you match against object attributes in Python's pattern matching?

A: Yes. Class patterns like case Point(x=0, y=y) can destructure objects by matching against their attributes.

Q: What is the wildcard pattern in Python's match statement?

A: case _: matches anything (like a default case). The _ is a special pattern that never binds a variable.

Q: What did Python 3.12 do with the GIL?

A: Python 3.12 began the work for per-interpreter GIL (PEP 684), allowing each sub-interpreter to have its own GIL.

Q: What is the experimental JIT compiler in Python 3.13?

A: A copy-and-patch JIT compiler that generates machine code for hot Python bytecode. It is an early-stage feature that lays groundwork for future performance improvements.


22. Quick-Fire Trivia & Rapid Recall

Q: What is the walrus operator's PEP number?

A: PEP 572 — "Assignment Expressions."

Q: What is sys.maxsize?

A: The largest positive integer supported by the platform's Py_ssize_t type (typically 2^63 - 1 on 64-bit). It limits container sizes, not integer values.

Q: What does sys.platform return?

A: 'linux' on Linux, 'darwin' on macOS, 'win32' on Windows.

Q: What is the default recursion limit?

A: 1000 (check with sys.getrecursionlimit(), change with sys.setrecursionlimit()).

Q: Where do "spam" and "eggs" come from as Python variable names?

A: From Monty Python's famous "Spam" sketch, where everything on the menu contains spam. They replace the traditional "foo" and "bar" in Python examples.

Q: What is python -m this?

A: It prints The Zen of Python, same as import this.

Q: What Monty Python references exist in the Python stdlib?

A: The spam module (C extension example), spam/eggs in examples throughout documentation, the antigravity Easter egg (references XKCD which often features Python), and the "Spanish Inquisition" references in some test suites.

Q: What is Cython?

A: A superset of Python that compiles to C for performance. It allows adding C type declarations to Python code for dramatic speedups.

Q: What is mypyc?

A: A compiler that uses mypy type annotations to compile Python modules to C extensions. It powers mypy's own speedup.

Q: What is PyInstaller?

A: A tool that packages Python applications into standalone executables, bundling the interpreter and all dependencies.

Q: What is mypy?

A: The original static type checker for Python, created by Jukka Lehtosalo. It checks type annotations without running the code.

Q: Name three Python static type checkers besides mypy.

A: Pyright (Microsoft, used by Pylance in VS Code), pytype (Google), and Pyre (Facebook/Meta).

Q: What is the GIL's full name?

A: Global Interpreter Lock.

Q: What year did Python first appear on the TIOBE index top 3?

A: Python first reached the #1 spot on TIOBE in October 2021, though it had been in the top 3 since around 2018.

Q: How many keywords does Python 3.12 have?

A: 35 keywords. You can see them with import keyword; print(keyword.kwlist).

Q: What is __name__ set to when a module is imported?

A: The module's name (e.g., 'mymodule'). When run as a script, it is set to '__main__'.

Q: What is the dis module?

A: The disassembler module that converts Python bytecode into human-readable form. Useful for understanding CPython internals.

Q: What does sys.getdefaultencoding() return in Python 3?

A: 'utf-8'.

Q: What is __file__ in a module?

A: The path to the file from which the module was loaded. It is not defined for C extensions or built-in modules.

Q: What is __spec__ in a module?

A: A ModuleSpec object (added in Python 3.4) containing metadata about how the module was loaded, including its name, loader, and origin.

Q: What does python -c "expr" do?

A: Executes the given Python expression directly from the command line.

Q: What is the PYTHONPATH environment variable?

A: A colon-separated (semicolon on Windows) list of directories added to sys.path before the default entries.

Q: What is PYTHONSTARTUP?

A: An environment variable pointing to a Python file that is executed when the interactive interpreter starts. Useful for setting up custom helpers.

Q: What is sys.executable?

A: The path to the Python interpreter binary currently running.

Q: What is the compile() built-in?

A: It compiles a string of Python code into a code object that can be executed with exec() or eval(). It accepts 'exec', 'eval', or 'single' mode.

Q: What is the difference between exec() and eval()?

A: eval() evaluates a single expression and returns its value. exec() executes arbitrary statements but always returns None.

Q: What is getattr(obj, name, default) used for?

A: It retrieves an attribute by name string. If the attribute does not exist, it returns the default (or raises AttributeError if no default is given).

Q: What is hasattr(obj, name) equivalent to?

A: Calling getattr(obj, name) and catching AttributeError. It returns True if the attribute exists.

Q: What is vars(obj) equivalent to?

A: obj.__dict__ — it returns the __dict__ attribute of the object. Without an argument, vars() returns locals().

Q: What is dir() used for?

A: It returns a list of names in the current scope (no argument) or a list of valid attributes for an object. It calls __dir__() if defined.

Q: What is type() with one argument vs three arguments?

A: With one argument, type(obj) returns the type of the object. With three arguments, type(name, bases, dict) dynamically creates a new class.

Q: What is super() and how does it work?

A: super() returns a proxy object that delegates method calls to a parent or sibling class in the MRO. In Python 3, super() with no arguments works inside methods.

Q: What is the __init__.py file for?

A: It marks a directory as a Python package. It can be empty or contain initialization code. Since Python 3.3, namespace packages allow packages without __init__.py.

Q: What are namespace packages?

A: Packages without __init__.py (PEP 420, Python 3.3). They allow a single logical package to be split across multiple directories or even distributions.

Q: What does hash(-1) return in CPython?

A: -2. CPython's C-level hash function uses -1 as an error indicator, so it maps the hash value -1 to -2.

Q: What is the result of [] is []?

A: False. Each [] creates a new list object with a different identity.

Q: What is the result of () is ()?

A: True in CPython. Empty tuples are cached as singletons because they are immutable and commonly used.

Q: What does sys.getsizeof(1) return approximately?

A: About 28 bytes on a 64-bit system. Even small integers have significant overhead due to the object header.

Q: What is the difference between __import__() and importlib.import_module()?

A: Both import modules by name, but importlib.import_module() is the recommended approach. __import__() is the low-level function called by the import statement.

Q: What is object.__new__?

A: The static method that actually allocates memory for a new instance. All classes inherit it from object. It is called before __init__.

Q: What does isinstance() check that type() does not?

A: isinstance() checks the entire inheritance chain (including virtual subclasses registered with ABCs). type() only returns the exact type.

Q: What is the __weakref__ attribute?

A: A slot that allows weak references to an object. Objects with __slots__ need to explicitly include __weakref__ to support weak references.

Q: What is CPython's memory allocator?

A: CPython uses a custom memory allocator called pymalloc for small objects (up to 512 bytes). It uses memory pools and arenas to reduce fragmentation and improve performance.

Q: What is a "free list" in CPython?

A: A cache of recently deallocated objects of a specific type (like floats, tuples, lists) that can be reused instead of calling malloc(). This speeds up creation of frequently used objects.

Q: What is sys.getrefcount(obj)?

A: Returns the reference count for an object. The count is always at least 1 higher than expected because the function argument itself creates a temporary reference.

Q: What is the __annotations__ attribute?

A: A dictionary storing the annotations of a function, class, or module. For example, def f(x: int) -> str: results in f.__annotations__ == {'x': int, 'return': str}.

Q: What is a code object in Python?

A: An immutable object containing compiled bytecode, constants, variable names, and metadata for a function or module. Accessed via function.__code__.

Q: What does sys.argv contain?

A: A list of command-line arguments passed to the script. sys.argv[0] is the script name.

Q: What is os.environ?

A: A mapping object representing the environment variables. Changes to it affect the current process and any child processes.

Q: What does @property do under the hood?

A: It creates a data descriptor with __get__, __set__, and __delete__ methods. The getter is passed to property(), and setter/deleter are added via .setter and .deleter decorators.

Q: What is the __prepare__ method in metaclasses?

A: A classmethod on the metaclass that returns the namespace dict to use during class body execution. It allows custom namespace objects (like OrderedDict) for tracking definition order.

Q: What is __init_subclass__ vs a metaclass?

A: __init_subclass__ is simpler and covers many use cases (registering subclasses, validating class attributes). Metaclasses are more powerful but harder to compose — use __init_subclass__ when possible.

Q: What does the abc.abstractmethod decorator do?

A: It marks a method as abstract, preventing the class from being instantiated unless the method is overridden. The containing class must inherit from ABC or use ABCMeta.

Q: What is collections.abc.Hashable?

A: An abstract base class for objects that support hash(). You can check isinstance(obj, Hashable) to test if an object is hashable.

Q: What is the textwrap module useful for?

A: Wrapping and formatting plain text: wrap(), fill(), dedent(), indent(), and shorten() for truncating text with a placeholder.

Q: What does os.path.expanduser('~') return?

A: The current user's home directory path.

Q: What is the platform module?

A: It provides portable access to platform-identifying data: platform.system() returns 'Linux', 'Darwin', or 'Windows'. Also platform.python_version(), platform.machine(), etc.

Q: What does python -m site do?

A: It prints the site-packages paths, user site-packages path, and other configuration details.

Q: What is sys.stdin, sys.stdout, sys.stderr?

A: File objects corresponding to the interpreter's standard input, output, and error streams. They can be redirected.

Q: What does python -m venv myenv do?

A: Creates a virtual environment in the myenv directory with its own Python binary and isolated site-packages.

Q: What is pip freeze used for?

A: It outputs a list of installed packages and their versions in requirements.txt format, suitable for recreating the environment.

Q: What is a requirements.txt file?

A: A text file listing Python package dependencies, one per line, with optional version specifiers. Used by pip install -r requirements.txt.

Q: What is the wheel filename convention?

A: {name}-{version}(-{build})?-{python}-{abi}-{platform}.whl. For example: numpy-1.24.0-cp311-cp311-manylinux_2_17_x86_64.whl.

Q: What is manylinux?

A: A tag for Linux wheel files indicating compatibility across many Linux distributions. It defines a set of allowed system libraries, enabling portable binary wheels.

Q: What is sdist in Python packaging?

A: Source distribution — a tarball (.tar.gz) containing the source code and build instructions. Unlike wheels, sdists require building during installation.

Q: What does __all__ in __init__.py control?

A: What is exported when from package import * is used. It also serves as documentation of the package's public API.

Q: What is the __main__.py file for?

A: It makes a package executable with python -m package. The __main__.py file is executed when the package is run as a script.

Q: What is contextlib.closing() used for?

A: It wraps an object that has a .close() method but does not implement the context manager protocol, ensuring .close() is called when exiting the with block.

Q: What is itertools.product with the repeat parameter?

A: It computes the Cartesian product of an iterable with itself: product('AB', repeat=2) is equivalent to product('AB', 'AB').

Q: What is str.encode() and bytes.decode()?

A: str.encode('utf-8') converts a string to bytes. bytes.decode('utf-8') converts bytes to a string. The encoding defaults to UTF-8.

Q: What is the struct module's byte order prefixes?

A: > for big-endian, < for little-endian, = for native, ! for network (big-endian), @ for native with native size.

Q: What is __cached__ on a module?

A: The path to the compiled bytecode file (.pyc) for the module.

Q: What is the difference between is and == for None?

A: Always use is None because None is a singleton. == None would call __eq__ which could be overridden to return True for non-None objects.

Q: What is sys.flags?

A: A named tuple containing the settings of command-line flags like -O, -B, -v, etc.

Q: What does python -v do?

A: Verbose mode — prints a message each time a module is imported, showing which file is loaded.

Q: What is sys.modules?

A: A dictionary mapping module names to already-loaded module objects. It serves as a cache to prevent re-importing modules.

Q: What is the types module?

A: It provides access to special type objects like FunctionType, MethodType, ModuleType, GeneratorType, and SimpleNamespace.

Q: What is types.SimpleNamespace?

A: A simple class that allows attribute access on an object: ns = SimpleNamespace(x=1, y=2); ns.x returns 1. Useful as a lightweight alternative to classes or dicts.

Q: What does object.__subclasses__() return?

A: A list of all immediate subclasses of the class that are still alive in memory.

Q: What is classmethod vs staticmethod when used with inheritance?

A: classmethod receives the actual subclass as cls, enabling factory methods that return the correct subclass type. staticmethod has no access to the class, so it behaves identically regardless of which class calls it.

Q: What is __dict__ on a class vs an instance?

A: A class's __dict__ contains its methods and class attributes (as a mappingproxy). An instance's __dict__ contains only its instance attributes.

Q: What is a mappingproxy?

A: A read-only view of a dictionary, used for class __dict__ to prevent accidental modification of the class namespace through the dict interface.

Q: What is the @functools.lru_cache memory leak risk?

A: If the cached function receives large objects as arguments, those objects are kept alive by the cache even if no other references exist. Use maxsize to limit cache size.

Q: What does hash(float('inf')) return?

A: 314159 in CPython — a reference to pi.

Q: What is the time module's perf_counter() vs time()?

A: perf_counter() returns a high-resolution monotonic timer for measuring short durations. time() returns wall-clock time (epoch seconds) which can jump due to NTP adjustments.

Q: What is time.monotonic()?

A: A clock that cannot go backwards, even if system time is adjusted. Useful for measuring elapsed time.

Q: What is the calendar module?

A: It provides calendar-related functions: printing calendars, determining leap years, and iterating over months and weeks.

Q: What does calendar.isleap(year) check?

A: Whether the given year is a leap year according to the Gregorian calendar.

Q: What is str.isidentifier()?

A: It returns True if the string is a valid Python identifier. Use keyword.iskeyword() to additionally check if it is a reserved keyword.

Q: What does chr() and ord() do?

A: chr(n) returns the string character for Unicode code point n. ord(c) returns the Unicode code point for a single character string c. They are inverses.

Q: What is the collections.OrderedDict popitem(last=True) method?

A: It removes and returns a (key, value) pair. With last=True (default), it removes from the end (LIFO). With last=False, it removes from the beginning (FIFO).

Q: What is dict.setdefault(key, default)?

A: If key is in the dict, return its value. If not, insert key with default and return default. It is atomic (thread-safe in CPython due to the GIL).

Q: What does dict | other_dict do in Python 3.9+?

A: It creates a new dict with merged key-value pairs. Values from other_dict override those in dict for shared keys. |= does the merge in-place.

Q: What is the walrus operator officially called?

A: Assignment expression.

Q: What is the difference between list.copy() and list[:]?

A: They both create a shallow copy. list.copy() was added in Python 3.3 and is more readable. list[:] uses slice syntax for the same effect.

Q: What does reversed() require?

A: Either a sequence (with __len__ and __getitem__) or an object with a __reversed__ method. It returns a reverse iterator.

Q: What is the locale module?

A: It provides access to locale-specific formatting for numbers, currency, and dates. locale.setlocale() changes the locale for the current process.

Q: What is decimal.Decimal vs float for financial calculations?

A: Decimal provides exact decimal arithmetic without floating-point rounding errors, making it essential for financial calculations where exactness matters.

Q: What is math.factorial() used for?

A: Computing factorials: math.factorial(5) returns 120. It raises ValueError for negative numbers.

Q: What does math.gcd() compute?

A: The greatest common divisor. Since Python 3.9, it accepts multiple arguments: math.gcd(12, 18, 24) returns 6.

Q: What does math.lcm() compute, and when was it added?

A: The least common multiple. Added in Python 3.9, it accepts multiple arguments: math.lcm(4, 6, 10) returns 60.

Q: What is functools.singledispatch limited to?

A: It dispatches only on the type of the first argument. For multiple-dispatch (dispatching on types of multiple arguments), use third-party libraries like multipledispatch.

Q: What is the warnings module?

A: It provides a mechanism for issuing warning messages (like DeprecationWarning) that do not stop execution. Warnings can be filtered, silenced, or turned into exceptions.

Q: What is DeprecationWarning vs PendingDeprecationWarning?

A: DeprecationWarning is for features scheduled for removal. PendingDeprecationWarning is for features that may be deprecated in the future. By default, DeprecationWarning is shown in __main__ but hidden in imported modules.

Q: What is sys.float_info?

A: A named tuple containing information about the float type: max (largest representable float), min (smallest positive normalized float), epsilon (smallest difference between 1.0 and the next float), etc.

Q: What is math.inf vs sys.float_info.max?

A: math.inf is positive infinity (a special IEEE 754 value). sys.float_info.max is the largest finite representable float (approximately 1.8e+308).

Q: What is a Python "magic comment" for encoding?

A: A comment like # -*- coding: utf-8 -*- or # coding: utf-8 on the first or second line of a source file. It declares the source encoding. Not needed in Python 3 (UTF-8 is default).

Q: What is __doc__?

A: The docstring attribute of a function, class, or module. It is set from the first string literal in the body.

Q: What is the help() built-in?

A: It invokes the interactive help system. help(obj) displays the docstring and other information about the object. It uses the pydoc module internally.

Q: What is the __qualname__ attribute?

A: The qualified name of a class or function, showing the path from the module level. For a nested class method: Outer.Inner.method. Added in Python 3.3.

Q: What is memoryview used for?

A: It creates a view of the memory of a bytes-like object without copying. Useful for zero-copy slicing of large binary data like bytes, bytearray, or array.array.

Q: What is the with statement's full syntax since Python 3.1?

A: Multiple context managers in one statement: with open('a') as f1, open('b') as f2:. Python 3.10 also allows parenthesized multi-line form.

Q: What is os.walk() used for?

A: It generates (dirpath, dirnames, filenames) tuples for each directory in a tree, enabling recursive directory traversal.

Q: What is pathlib.Path.glob() used for?

A: Pattern matching for files within a directory tree: Path('.').glob('**/*.py') finds all Python files recursively.

Q: What is pathlib.Path.resolve() used for?

A: It returns the absolute path with all symlinks resolved and .. components eliminated.

Q: What does any(generator_expression) short-circuit?

A: Yes. any() stops iterating as soon as it finds a truthy value, and all() stops at the first falsy value. This makes them efficient for large iterables.

Q: What is itertools.repeat() commonly used with?

A: As a constant argument source for map() and zip(): list(map(pow, range(5), itertools.repeat(2))) gives [0, 1, 4, 9, 16].

Q: What does str.format_map() do?

A: Like str.format(**mapping) but takes a mapping directly without unpacking. Useful with defaultdict to handle missing keys gracefully.

Q: What is the abc.ABCMeta metaclass?

A: The metaclass used by ABC. It enables register() for virtual subclasses and tracks which abstract methods need implementation.

Q: What is a virtual subclass in Python's ABC framework?

A: A class registered with MyABC.register(SomeClass) that passes isinstance() and issubclass() checks for the ABC without actually inheriting from it.

Q: What does __subclasshook__ do?

A: An ABC classmethod that customizes issubclass() behavior. It can return True, False, or NotImplemented to override the default subclass check.

Q: What is the io module?

A: It provides Python's main I/O implementation with text streams (TextIOWrapper), binary streams (BufferedReader, BufferedWriter), and raw I/O (FileIO).

Q: What is io.StringIO used for?

A: An in-memory text stream that behaves like a file object. Useful for testing or capturing output: buf = StringIO(); print('hello', file=buf); buf.getvalue().

Q: What is io.BytesIO used for?

A: An in-memory binary stream. Useful for working with binary data using file-like APIs without actual files.

Q: What does object.__repr__ return by default?

A: Something like <ClassName object at 0x7f...> — the class name and memory address.

Q: What is the @property deleter?

A: The third component of a property: @attr.deleter defines what happens when del obj.attr is called. All three (getter, setter, deleter) are optional.

Q: What is __slots__ inheritance behavior?

A: __slots__ in a subclass only adds the slots defined in that class — it does not replace parent slots. If any class in the hierarchy lacks __slots__, instances will still have __dict__.

Q: What is typing.TypeVarTuple used for?

A: Added in Python 3.11 (PEP 646), it represents a variadic number of types. Used for typing functions that accept variable numbers of arguments of different types, like tensor shapes.

Q: What is typing.Required and typing.NotRequired for TypedDict?

A: Added in Python 3.11, they mark individual fields in a TypedDict as required or optional, allowing mixed required/optional fields in a single total=True or total=False TypedDict.

Q: What is the @typing.dataclass_transform decorator?

A: Added in Python 3.11 (PEP 681), it tells type checkers that a decorator or base class creates dataclass-like classes, enabling proper type checking for ORMs and similar frameworks.

Q: What does sys.exit() actually raise?

A: SystemExit exception. It does not immediately terminate — it can be caught by except BaseException or except SystemExit.

Q: What is os._exit() and when is it used?

A: It exits immediately without cleanup (no atexit handlers, no flushing buffers, no finally blocks). Used in child processes after os.fork() to avoid running parent cleanup code.

Q: What is the signal module used for?

A: Handling Unix signals in Python: signal.signal(signal.SIGTERM, handler) registers a handler for graceful shutdown.

Q: What is multiprocessing.Queue vs queue.Queue?

A: queue.Queue is thread-safe for use between threads. multiprocessing.Queue works across processes using pipes and serialization.

Q: What is threading.Event?

A: A synchronization primitive where one thread signals an event and other threads wait for it: event.set(), event.wait(), event.clear().

Q: What is threading.Condition?

A: A synchronization primitive combining a lock with the ability to wait for a condition: condition.wait(), condition.notify(), condition.notify_all().

Q: What is asyncio.sleep() vs time.sleep()?

A: asyncio.sleep() is non-blocking — it yields control back to the event loop. time.sleep() blocks the entire thread, including the event loop.

Q: What is aiofiles?

A: A third-party library providing async file I/O for asyncio, since the standard library's file operations are all synchronous and would block the event loop.

Q: What does sys.settrace() do?

A: It registers a trace function called for each line of Python execution. Used by debuggers and profilers. Replaced by the lower-overhead sys.monitoring in Python 3.12.

Q: What is sys.setprofile() used for?

A: It registers a profiling function called on function calls and returns. Less granular than settrace() but lower overhead.

Q: What is the cProfile module?

A: A deterministic profiler that records how many times each function is called and how long each call takes. Invoke with python -m cProfile script.py.

Q: What is the profile module vs cProfile?

A: Both are deterministic profilers with the same API. cProfile is a C extension (faster, recommended). profile is pure Python (can be extended more easily).

Q: What does python -m py_compile script.py do?

A: It compiles a Python source file to bytecode (.pyc), useful for syntax checking without executing the code.

Q: What is compileall used for?

A: python -m compileall directory compiles all .py files in a directory tree to .pyc files. Used when deploying to ensure bytecode is pre-compiled.

Q: What is the linecache module?

A: It reads lines from Python source files, with caching. Used internally by the traceback module to display source lines in tracebacks.

Q: What is fnmatch used for?

A: Unix filename pattern matching: fnmatch.fnmatch('file.py', '*.py') returns True. It supports *, ?, [seq], and [!seq] patterns.

Q: What is glob.glob() used for?

A: Finding files matching a Unix-style pattern: glob.glob('**/*.py', recursive=True) finds all Python files recursively.

Q: What is the subprocess.PIPE constant?

A: It indicates that a pipe should be created for stdin, stdout, or stderr, allowing the parent process to communicate with the child process.

Q: What is subprocess.Popen vs subprocess.run?

A: run() is a high-level convenience function that waits for completion. Popen is the low-level class for more control: non-blocking execution, streaming I/O, and process management.

Q: What is the select module?

A: It provides I/O multiplexing: monitoring multiple file descriptors for readability/writability. It wraps select(), poll(), and epoll() system calls.

Q: What is selectors module?

A: A higher-level I/O multiplexing library (Python 3.4+) that wraps select, providing a simpler API and automatically choosing the best available implementation.

Q: What is the socket module?

A: Low-level networking: creating TCP/UDP sockets, binding, listening, connecting, sending, and receiving data.

Q: What is ssl.create_default_context() for?

A: It creates an SSL context with secure default settings (certificate verification, modern TLS versions). Always use it instead of bare ssl.SSLContext().

Q: What is urllib.parse.urlencode() used for?

A: Converting a dictionary to a URL-encoded query string: urlencode({'q': 'python', 'page': '1'}) returns 'q=python&page=1'.

Q: What is urllib.parse.urlparse() used for?

A: Parsing a URL into its components: scheme, netloc, path, params, query, and fragment.

Q: What is the email module?

A: It provides tools for parsing, creating, and sending email messages, including MIME multipart messages with attachments.

Q: What is smtplib used for?

A: Sending emails via SMTP: creating an SMTP connection, authenticating, and sending messages.

Q: What is sqlite3 in the standard library?

A: A built-in interface to SQLite databases. It requires no separate server and stores the entire database in a single file. Included since Python 2.5.

Q: What is a Python wheel's tag format?

A: {python tag}-{abi tag}-{platform tag}. For example, cp311-cp311-manylinux_2_17_x86_64 means CPython 3.11, CPython 3.11 ABI, 64-bit Linux.

Q: What is py3-none-any in a wheel filename?

A: A pure Python wheel: works with any Python 3 version, no ABI dependency, any platform. Example: requests-2.31.0-py3-none-any.whl.

Q: What is pip install -e . (editable install)?

A: It installs a package in development mode — the package is linked (not copied) so changes to source code take effect immediately without reinstalling.

Q: What is __import__ hook?

A: Python's import system can be customized by adding finder objects to sys.meta_path or sys.path_hooks. These hooks intercept import statements and can load modules from custom sources.

Q: What is a Python namespace?

A: A mapping from names to objects. Examples: the set of built-in names, global names in a module, and local names in a function. Namespaces are implemented as dictionaries.

Q: What is exec() dangerous for?

A: It executes arbitrary Python code from a string, which is a security risk if the string comes from untrusted input. It also makes code harder to analyze and debug.

Q: What is the operator module?

A: It provides function equivalents of Python operators: operator.add(a, b) is equivalent to a + b. Useful as arguments to map(), reduce(), and sorted().

Q: What is typing.ClassVar used for?

A: Marking an annotation as a class variable (not an instance variable) in dataclasses and type-checked code: count: ClassVar[int] = 0.

Q: What is typing.Optional[X] equivalent to?

A: Union[X, None] or X | None (Python 3.10+). It indicates the value can be of type X or None.

Q: What is typing.Union used for?

A: Expressing that a value can be one of several types: Union[int, str]. In Python 3.10+, the | syntax replaces it: int | str.

Q: What is typing.Any?

A: A special type that is compatible with every type. Variables annotated with Any are not type-checked. It is the "escape hatch" from the type system.

Q: What is typing.cast() used for?

A: Telling the type checker to treat a value as a specific type without any runtime effect: cast(int, some_value). It is purely a hint for static analysis.

Q: What is a TYPE_CHECKING guard?

A: if TYPE_CHECKING: is a block that only runs during type checking, not at runtime. Used for importing types needed only for annotations, avoiding circular imports.

Q: What is typing.Callable used for?

A: Annotating callable objects: Callable[[int, str], bool] describes a function taking an int and str and returning bool.

Q: What is typing.Awaitable?

A: A type hint for objects that can be awaited: coroutines, tasks, futures.

Q: What is typing.AsyncIterator?

A: A type hint for async iterators — objects implementing __aiter__ and __anext__.

Q: What is the pydoc module?

A: It generates documentation from Python modules: python -m pydoc module_name displays documentation, and python -m pydoc -b starts a documentation server.

Q: What is unittest.TestCase.setUp() vs setUpClass()?

A: setUp() runs before every test method. setUpClass() (a classmethod) runs once before all tests in the class — useful for expensive setup like database connections.

Q: What is pytest.fixture(scope='session')?

A: A fixture that runs once per test session (all tests). Useful for expensive setup that should be shared across all tests.

Q: What is pytest.approx() used for?

A: Comparing floating-point numbers in assertions: assert 0.1 + 0.2 == pytest.approx(0.3). It handles floating-point imprecision.

Q: What is unittest.mock.sentinel?

A: Unique objects useful as placeholders in tests: sentinel.some_value creates a unique object that can only be equal to itself.

Q: What is pytest.monkeypatch?

A: A built-in fixture for safely modifying objects, dictionaries, and environment variables during tests: monkeypatch.setattr(), monkeypatch.setenv(), etc.

Q: What is Django's migration system?

A: An automated system that tracks database schema changes. makemigrations detects model changes and creates migration files. migrate applies them to the database.

Q: What is Django's manage.py?

A: A command-line utility for Django projects: python manage.py runserver, python manage.py migrate, python manage.py createsuperuser, etc.

Q: What template engine does Django use by default?

A: The Django Template Language (DTL), though it also supports Jinja2 as an alternative backend.

Q: What is Flask's g object?

A: A per-request global namespace for storing data during a request lifecycle. It is reset between requests.

Q: What is Pydantic v2's key change from v1?

A: Pydantic v2 rewrote the core validation engine in Rust (pydantic-core), making it 5-50x faster than v1. It also uses model_validate() instead of parse_obj().

Q: What is Starlette?

A: A lightweight ASGI framework that provides routing, middleware, WebSocket support, and background tasks. FastAPI is built on top of it.

Q: What is uvloop?

A: A fast, drop-in replacement for asyncio's event loop, written in Cython and based on libuv. It can make asyncio 2-4x faster.

Q: What NumPy function creates an array of zeros?

A: np.zeros(shape) creates an array filled with zeros. np.ones(shape) for ones, np.empty(shape) for uninitialized memory.

Q: What is the difference between NumPy's np.array() and np.asarray()?

A: np.array() always creates a new array. np.asarray() only creates a new array if the input is not already an ndarray, avoiding unnecessary copies.

Q: What is NumPy's dtype?

A: The data type of array elements: np.float64, np.int32, np.bool_, etc. It determines storage size and behavior.

Q: What is Pandas groupby() used for?

A: Splitting a DataFrame into groups based on column values, applying a function to each group, and combining results — the "split-apply-combine" pattern.

Q: What is the apply() method in Pandas?

A: It applies a function along an axis of a DataFrame or to each element of a Series. It is flexible but slower than vectorized operations.

Q: What does pandas.DataFrame.merge() do?

A: SQL-style joins between DataFrames on columns or indexes. Supports inner, outer, left, and right join types.

Q: What is scipy.optimize.minimize()?

A: A function for finding the minimum of a scalar function, supporting multiple algorithms (Nelder-Mead, BFGS, L-BFGS-B, etc.).

Q: What is a Jupyter kernel?

A: The computation engine that executes code in a notebook. Each kernel runs a specific language (IPython for Python). Multiple kernels can be installed for different languages or environments.

Q: What is the json module's cls parameter?

A: It specifies a custom JSONEncoder subclass for serializing objects that are not JSON-serializable by default: json.dumps(obj, cls=CustomEncoder).

Q: What is json.JSONDecodeError?

A: The exception raised when json.loads() or json.load() encounters invalid JSON. It is a subclass of ValueError.

Q: What does hashlib provide?

A: Secure hash functions: hashlib.sha256(data).hexdigest(). It supports MD5, SHA-1, SHA-256, SHA-512, BLAKE2, and more.

Q: What is hmac module used for?

A: Creating keyed-hash message authentication codes for verifying message integrity and authenticity: hmac.new(key, message, hashlib.sha256).hexdigest().

Q: What is base64 encoding used for in Python?

A: Encoding binary data as ASCII text: base64.b64encode(data). Commonly used for embedding binary data in JSON, URLs, or email.

Q: What is collections.abc.MutableMapping?

A: An abstract base class for dict-like objects. Implementing __getitem__, __setitem__, __delitem__, __len__, and __iter__ gives you the full mapping API for free.

Q: What is zipimport?

A: A built-in importer that allows importing Python modules directly from ZIP files. It is used by python -m zipapp and is how Ansible's Ansiballz module transfer works.

Q: What is Ansible's Ansiballz?

A: The mechanism Ansible uses to transfer Python modules to remote hosts. It packages the module and its dependencies into a ZIP file that is executed via zipimport.

Q: What does python -m ensurepip do?

A: It bootstraps pip into a Python installation that does not have it. Useful for minimal Python installations.

Q: What is sysconfig used for?

A: Accessing Python's configuration: installation paths, compiler flags, platform tags. sysconfig.get_paths() returns where packages are installed.

Q: What is the dataclasses.make_dataclass() function?

A: Dynamically creates a dataclass from a name and list of fields: Point = make_dataclass('Point', ['x', 'y']). Useful for runtime dataclass generation.

Q: What is collections.abc.Iterator vs collections.abc.Iterable?

A: Iterable defines __iter__(). Iterator defines both __iter__() and __next__(). All iterators are iterable, but not all iterables are iterators (e.g., lists are iterable but not iterators).

Q: What is the decimal module's ROUND_HALF_EVEN rounding mode?

A: Banker's rounding — rounds to the nearest even number when the value is exactly halfway. This is the default rounding mode for Decimal and Python's built-in round().

Q: What is the fractions.Fraction.limit_denominator() method?

A: It finds the closest rational approximation with a denominator at most max_denominator: Fraction(3.141592653).limit_denominator(100) gives Fraction(311, 99).

Q: What is int.as_integer_ratio() added in Python 3.8?

A: It returns a pair of integers (numerator, denominator) equal to the integer with a positive denominator: (10).as_integer_ratio() returns (10, 1).

Q: What is the unicodedata module?

A: It provides access to the Unicode Character Database: unicodedata.name('A') returns 'LATIN CAPITAL LETTER A', and unicodedata.normalize() handles Unicode normalization forms.

Q: What is Python's match statement OR pattern?

A: Use | to match multiple patterns: case 200 | 201 | 202: matches any of those status codes.

Q: What is Python's match statement mapping pattern?

A: case {"status": 200, "body": body}: matches dictionaries with specific keys and captures values. Extra keys are allowed.

Q: What is Python's match statement sequence pattern?

A: case [first, *rest]: matches sequences, capturing the first element and remaining elements in a list.

Q: What does sys.getswitchinterval() return?

A: The thread switch interval in seconds (default 0.005 = 5ms). This controls how often the GIL is released to allow other threads to run.

Q: What is ctypes used for?

A: Calling functions in C shared libraries from Python without writing C extension code. It provides C-compatible data types and function prototypes.

Q: What is cffi (C Foreign Function Interface)?

A: A third-party library for calling C code from Python. It is more Pythonic than ctypes and is used by PyPy for C extension compatibility.

Q: What is the difflib module?

A: It provides tools for comparing sequences: unified_diff() and context_diff() for text comparisons, SequenceMatcher for computing similarity ratios.

Q: What is difflib.get_close_matches() used for?

A: Finding strings similar to a target: get_close_matches('appel', ['apple', 'ape', 'maple']) returns ['apple', 'maple']. Useful for "did you mean?" suggestions.

Q: What is the csv module?

A: Reading and writing CSV files with csv.reader(), csv.writer(), csv.DictReader(), and csv.DictWriter(). It handles quoting, escaping, and different dialects.

Q: What is configparser used for?

A: Reading and writing INI-style configuration files with sections, keys, and values. Similar to Windows .ini files.

Q: What is argparse.FileType?

A: A factory for argparse that opens files: parser.add_argument('input', type=argparse.FileType('r')) automatically opens the file for reading.

Q: What is the concurrent.futures.as_completed() function?

A: It yields Future objects as they complete, regardless of submission order. Useful for processing results as they become available.

Q: What is asyncio.wait_for() used for?

A: Wrapping a coroutine with a timeout: await asyncio.wait_for(coro, timeout=5.0) raises asyncio.TimeoutError if the coroutine does not complete in time.

Q: What is asyncio.to_thread() added in Python 3.9?

A: It runs a synchronous function in a separate thread: await asyncio.to_thread(blocking_io_func). This prevents blocking the event loop.

Q: What is asyncio.create_task() vs await?

A: await coro() runs and waits for a single coroutine. asyncio.create_task(coro()) schedules it to run concurrently without waiting, returning a Task that can be awaited later.

Q: What is the __aenter__ and __aexit__ protocol?

A: The async context manager protocol, used with async with. __aenter__ is an async method called on entry, __aexit__ on exit.

Q: What is __aiter__ and __anext__?

A: The async iterator protocol. __aiter__ returns the async iterator, __anext__ returns an awaitable that yields the next value or raises StopAsyncIteration.

Q: What is collections.abc.Coroutine?

A: An abstract base class for coroutine objects (those created by async def functions). It defines send(), throw(), and close() methods.

Q: What is sys.exc_info() used for?

A: Returns a tuple (type, value, traceback) of the exception currently being handled. Returns (None, None, None) if no exception is being handled.

Q: What is the contextlib.aclosing() context manager?

A: Added in Python 3.10, it calls aclose() on an async generator when exiting the async with block, ensuring cleanup.

Q: What is typing.get_type_hints() used for?

A: It resolves string annotations to actual types, handling forward references and from __future__ import annotations. More reliable than accessing __annotations__ directly.

Q: What is the enum.verify decorator added in Python 3.11?

A: It validates enum classes according to named rules: @verify(UNIQUE) ensures no duplicate values, @verify(CONTINUOUS) ensures no gaps in integer values.

Q: What is functools.reduce with an initial value?

A: reduce(func, iterable, initializer) starts accumulation from the initializer instead of the first element. Without it, an empty iterable raises TypeError.

Q: What does list.extend() do vs list.append()?

A: append(x) adds x as a single element. extend(iterable) adds each element of the iterable individually. lst.append([1,2]) adds one list element; lst.extend([1,2]) adds two integer elements.