Python 3.15: Why protect process-spawning entry code with if __name__ == '__main__'? Importing the module in a child should not recursively start new worker processes.
Python 3.15: How does quote_plus encode a space differently from quote? quote_plus uses +; quote uses %20.
Python 3.15: Which urlencode option turns {'tag': ['a', 'b']} into repeated tag parameters? doseq=True.
Python 3.15: What is list(itertools.pairwise([2, 4, 8]))? [(2, 4), (4, 8)].
Python 3.15: Why is caching a function whose result depends on changing external state potentially incorrect? The same arguments may return an old cached result without re-reading that state.
Python 3.15: What does re.search return when the pattern does not match? None.
Python 3.15: Which datetime.datetime method parses a string according to an explicit format? datetime.datetime.strptime(text, format_string).
Python 3.15: What is math.prod([2, 3, 4])? 24.
Python 3.15: What is the return type of gzip.compress(b'hello')? bytes containing a gzip-compressed stream.
Python 3.15: What happens when Future.result() is called after the worker raised an exception? It raises that worker exception in the caller.
Python 3.15: How does json.load differ from json.loads? load reads a file-like object; loads parses an in-memory JSON string, bytes or bytearray.
Python 3.15: How can os.getenv read APP_MODE while returning 'dev' when it is absent? os.getenv('APP_MODE', 'dev').
Python 3.15: What does Fraction.limit_denominator(max_denominator) find? A nearby rational value whose denominator does not exceed the supplied limit.
Python 3.15: Why can itertools.cycle use growing memory while first traversing a large input? It saves elements so that it can replay them on later cycles.
Python 3.15: What does nargs='+' require for an argparse argument? One or more values, collected into a list.
Python 3.15: How should a variable value be supplied to sqlite3 instead of formatting it into SQL text? Use a placeholder and a separate parameter sequence or mapping.
Python 3.15: Which argparse class constructs a command-line argument parser? argparse.ArgumentParser.
Python 3.15: Can random.randrange(2, 8) return 8? No. Its upper bound is excluded.
Python 3.15: How do you declare a required positional argument named filename with argparse? parser.add_argument('filename').
Python 3.15: In which order does ExitStack run registered exit callbacks? Last registered, first called.
Python 3.15: What constraint do ProcessPoolExecutor functions, arguments and results normally need to satisfy? They must be picklable, and workers must be able to import the required definitions.
Python 3.15: What time-zone information is missing from a naive datetime? It has no usable UTC-offset information identifying its time zone.
Python 3.15: How do you open a text file with UTF-8 decoding regardless of ambient encoding settings? open(path, encoding='utf-8').
Python 3.15: Can Future.cancel normally stop a task that is already running? No. Cancellation succeeds only before execution has started.
Python 3.15: Does typing.cast(int, value) convert value into an integer? No. It returns value unchanged and supplies a hint to the type checker.
Python 3.15: Which tarfile extraction filter is the default starting with Python 3.14, including 3.15? 'data', which rejects several dangerous path and link cases but does not eliminate every risk.
Python 3.15: Why is shell=True risky with an interpolated untrusted argument? The shell can interpret metacharacters as commands rather than literal argument data.
Python 3.15: Which standard-library function escapes <, > and & for ordinary HTML text content? html.escape(text); quote=True also escapes quote characters.
Python 3.15: Why should async code normally re-raise CancelledError after cleanup? Swallowing it can break cancellation and structured-concurrency behavior.
Python 3.15: Where does traceback.print_exc write by default? sys.stderr.
Python 3.15: How many bytes does hashlib.sha256(data).digest() return? 32 bytes.
Python 3.15: Can a ? placeholder safely stand in for an SQL table name? No. Placeholders bind values, not SQL identifiers; choose identifiers from a controlled set.
Python 3.15: What two values does tempfile.mkstemp return? An open file descriptor and an absolute pathname; the caller must close and remove the file.
Python 3.15: Which standard logging level is more severe than ERROR? CRITICAL.
Python 3.15: What does urllib.parse.parse_qs('x=1&x=2') return? {'x': ['1', '2']}.
Python 3.15: Which Path method removes a file or symbolic link rather than a directory tree? path.unlink(); missing_ok=True tolerates a missing path.
Python 3.15: What is json.dumps's default response to an unsupported custom object? It raises TypeError unless a suitable default handler or encoder is supplied.
Python 3.15: Does Executor.map yield results in task completion order? No. It yields them in input order, even when later tasks finish first.
Python 3.15: Does shutil.copy2 guarantee copying every kind of filesystem metadata? No. It attempts metadata preservation, but platform-specific metadata may be lost.
Python 3.15: What Python type does a binary stream's read() normally return? bytes; binary streams do not perform text decoding.
Python 3.15: Can a handler's higher level discard a record that passed the logger's level? Yes. The handler applies its own level threshold.
Python 3.15: Why can the same log message appear twice when handlers are attached to a logger and an ancestor? Propagation can deliver the record to handlers at both levels.
Python 3.15: What is the default outcome when strict UTF-8 decoding meets invalid bytes? A UnicodeDecodeError is raised.
Python 3.15: Which copytree option permits copying into already existing destination directories? dirs_exist_ok=True; matching destination files can be overwritten.
Python 3.15: Which datetime method formats a value using directives such as %Y-%m-%d? strftime(format_string).
Python 3.15: Where is an exception raised inside a with block delivered to a generator context manager? At the generator's yield expression.
Python 3.15: How can re.sub replace only the first occurrence of a pattern? Pass count=1.
Python 3.15: Which hmac helper avoids ordinary equality's content-dependent early exit when comparing authentication tags? hmac.compare_digest(a, b); supply compatible types.
Python 3.15: How should a dataclass field obtain a separate empty list for each instance? Use field(default_factory=list).
Python 3.15: How do you configure a Mock to return 42 when called? Set mock.return_value = 42, or construct Mock(return_value=42).
Python 3.15: What does TestCase.subTest provide inside a loop of related cases? Separate reporting of each parameterized block while allowing later iterations to run after a failure.
Python 3.15: What does asyncio.run(coro) provide for a top-level coroutine? It manages an event loop and runs the coroutine to completion, then performs loop cleanup.
Python 3.15: What does stack.enter_context(cm) return? The value returned by cm.__enter__(), while registering its exit method for cleanup.
Python 3.15: What does shutil.which('python3') return when no matching executable is found? None.
Python 3.15: How do you retrieve the Color member whose value equals 7? Color(7).
Python 3.15: Why does ipaddress.ip_network('192.0.2.5/24') raise ValueError by default? Host bits are set; strict=False allows them and normalizes to the network address.
Python 3.15: Which attribute does functools.wraps set to reference the original callable? __wrapped__.
Python 3.15: What does cursor.fetchall return when there are no remaining rows? An empty list.
Python 3.15: What remains after d = deque([1, 2], maxlen=2) and d.append(3)? deque([2, 3], maxlen=2); appending discards the oldest item from the opposite end.
Python 3.15: Does dt.replace(tzinfo=zone) convert dt's clock time to that zone? No. It changes the attached zone information without adjusting the clock fields.
Python 3.15: Which mapping binds :name in execute('SELECT :name', ...)? {'name': 'Ada'}, using the parameter name without the colon as the key.
Python 3.15: Is shlex.quote a general escaping solution for Windows cmd.exe arguments? No. It is designed for Unix/POSIX-style shells.
Python 3.15: Which argparse action makes --verbose set a value to True when present? action='store_true'.
Python 3.15: Does os.chdir change the working directory only for the calling function? No. It changes the process working directory, affecting other code using relative paths.
Python 3.15: What does typing.Optional[int] permit beyond int? None; it does not mean that a function argument may be omitted.
Python 3.15: Which ArgumentParser method creates a group of options that cannot be supplied together? add_mutually_exclusive_group().
Python 3.15: Which decorator helper preserves a wrapped function's name and documentation on a wrapper? functools.wraps(wrapped_function).
Python 3.15: Does dataclasses.asdict perform only a shallow extraction of field references? No. It recursively converts nested dataclasses and containers and deep-copies other values.
Python 3.15: What does os.scandir yield instead of bare file-name strings? DirEntry objects, which provide names, paths and file-type information.
Python 3.15: Which flag makes the dot wildcard match newline characters too? re.DOTALL, also available as re.S.
Python 3.15: Does Path.iterdir recursively visit a directory's descendants? No. It yields paths for the directory's immediate children, in arbitrary order.
Python 3.15: Which urllib.parse.quote argument also percent-encodes slash characters? safe=''.
Python 3.15: Why should a groupby group's values be consumed or saved before advancing the outer iterator? Groups share the underlying iterator, so advancing it makes earlier group data unavailable.
Python 3.15: What does base64.b64encode(b'hi') return? b'aGk=', a bytes value.
Python 3.15: For class Color(Enum): RED = 7, what does Color.RED.value return? 7.
Python 3.15: What object does ArgumentParser.parse_args normally return? An argparse.Namespace containing attributes for the parsed arguments.
Python 3.15: Does time.sleep pause only an asyncio task or the calling operating-system thread? It blocks the calling thread; use await asyncio.sleep(...) for cooperative async waiting.
Python 3.15: What does heapq.heappushpop([2, 5, 7], 1) return? 1; the pushed item is the smallest, so it is returned immediately.
Python 3.15: What does pathlib.PurePosixPath('notes.txt').with_suffix('.md') return? PurePosixPath('notes.md'); it constructs a new path without renaming a file.
Python 3.15: Which newline setting should be used when opening text files for csv.reader or csv.writer? newline='', allowing the csv module to handle line endings itself.
Python 3.15: What date is datetime.date(2024, 2, 28) + datetime.timedelta(days=1)? 2024-02-29; 2024 is a leap year.
Python 3.15: Why are raw string literals often used for regular expression patterns? They prevent Python string-literal escapes from consuming backslashes intended for the regex parser.
Python 3.15: How does functools.cache differ from a size-limited lru_cache? It is an unbounded memoization cache, equivalent to lru_cache(maxsize=None).
Python 3.15: With autocommit=False, which connection method saves the current transaction's changes? connection.commit().
Python 3.15: What does random.shuffle(items) return after shuffling a mutable sequence? None; it shuffles the sequence in place.
Python 3.15: Which high-level subprocess function runs a command, waits for completion and returns a CompletedProcess? subprocess.run(...).
Python 3.15: What is statistics.mean([2, 4, 9])? 5.
Python 3.15: Which re flag enables case-insensitive matching? re.IGNORECASE, also available as re.I.
Python 3.15: What does with contextlib.suppress(FileNotFoundError) suppress? Only matching FileNotFoundError exceptions from the block, not all exceptions.
Python 3.15: Which concurrent.futures helper yields futures as they finish? as_completed(futures).
Python 3.15: Which parse_qs option preserves a query parameter whose value is empty? keep_blank_values=True.
Python 3.15: Does itertools.groupby combine equal keys that occur in separated parts of an unsorted input? No. It groups consecutive equal keys; sort first when all equal keys must be grouped together.
Python 3.15: What does cursor.fetchone return when no row remains? None.
Python 3.15: How can unittest verify that an operation raises ValueError? Run the operation inside with self.assertRaises(ValueError):.
Python 3.15: Do runtime checks against @runtime_checkable Protocol verify complete method signatures? No. They check required attribute presence, not full type signatures.
Python 3.15: Why can TestCase.addCleanup be safer than relying only on tearDown for acquired resources? Registered cleanup functions run even if setUp subsequently fails.
Python 3.15: Which statistics function uses the sample-variance denominator n − 1? statistics.variance(data).
Python 3.15: Which Python value corresponds to SQL NULL in sqlite3 bindings and results? None.
Python 3.15: What happens to a threading.Lock acquired through with lock when the block raises? The lock is released during context exit.
Python 3.15: Which unicodedata operation converts canonically equivalent text to NFC form? unicodedata.normalize('NFC', text).
Python 3.15: Does leaving with connection automatically close a sqlite3 connection? No. Close it explicitly or use a separate closing context manager.
Python 3.15: How do you move an in-memory stream back to its beginning? Call stream.seek(0).
Python 3.15: Which logging component controls a record's textual layout? A Formatter.
Python 3.15: What does struct.unpack('!H', b'\x02\x01') return? (513,), a one-element tuple.
Python 3.15: What happens to integer dictionary keys after a JSON encode/decode round trip? They become strings, because JSON object member names are strings.
Python 3.15: Which b64decode option rejects non-alphabet characters instead of discarding them by default? validate=True.
Python 3.15: What does shlex.split('tool "two words"') return in its default POSIX mode? ['tool', 'two words'].
Python 3.15: Does constructing a TypedDict produce an object that enforces its declared value types at runtime? No. It produces an ordinary dictionary; the declared structure is for type checking.
Python 3.15: For Point = collections.namedtuple('Point', 'x y'), what does Point(2, 5).y return? 5.
Python 3.15: Can asyncio.run be called in a thread that already has a running event loop? No. Await the coroutine from the existing loop instead.
Python 3.15: How do you retrieve the named group 'code' from a successful match object m? m.group('code').
Python 3.15: Which unittest.mock class models an asynchronous callable whose result can be awaited? AsyncMock.
Python 3.15: How do you prevent os.walk(topdown=True) from descending into a listed subdirectory? Remove its name from the yielded dirnames list in place.
Python 3.15: What does math.comb(5, 2) count? The 10 unordered selections of two items from five distinct items.
Python 3.15: Which subprocess.run argument sends data to the child's standard input? input=...; use str in text mode and bytes in binary mode.
Python 3.15: Which json.loads argument lets JSON fractional numbers become Decimal objects? parse_float=decimal.Decimal.
Python 3.15: Which statistics function computes population variance with denominator n? statistics.pvariance(data).
Python 3.15: What exception can subprocess.run raise if the child exceeds timeout? subprocess.TimeoutExpired, after killing and waiting for the child process.
Python 3.15: When gather propagates one child's exception by default, are all other children automatically cancelled? No. Other children generally continue running; this differs from TaskGroup failure handling.
Python 3.15: What does a hash object's copy() method let you reuse? The current hashing state, so different suffixes can share an already processed prefix.
Python 3.15: What Python type does a text stream's read() normally return? str; decoding converts stored bytes into text.
Python 3.15: What does b'' from a connected TCP socket's recv usually indicate? The peer has closed its sending side and no more data remains to read.
Python 3.15: Does calling an async def function immediately run its body to completion? No. It normally creates a coroutine object, which must be awaited or scheduled.
Python 3.15: Why is contextlib.redirect_stdout unsafe as a general solution for concurrent threads? It changes process-global sys.stdout, so other threads can be affected.
Python 3.15: Should random.choice generate a password-reset token? No. Use secrets, which is intended for security-sensitive randomness.
Python 3.15: How can a simulation use its own reproducible random state without reseeding the module-global generator? Create a separate random.Random(seed) instance.
Python 3.15: If setUp succeeds, does tearDown normally run when the test method fails? Yes. It still runs after the test method's failure.
Python 3.15: After heapq.heapify(values), which element is stored at values[0] if the heap is nonempty? The smallest element.
Python 3.15: Does Queue.join mean that the worker threads themselves have exited? No. It waits for the unfinished-task count to reach zero.
Python 3.15: Which threading primitive lets one thread signal an event that other threads can wait for? threading.Event.
Python 3.15: Which math function offers more accurate summation of floating-point values than a naive running total? math.fsum(iterable).
Python 3.15: What does operator.itemgetter('name')({'name': 'Ada'}) return? 'Ada'.
Python 3.15: What does an absent key return from a Counter without inserting a count? 0.
Python 3.15: What does pathlib.PurePosixPath('logs') / 'today.txt' represent? The relative path logs/today.txt; / joins path components.
Python 3.15: What can await asyncio.sleep(0) do in a long-running coroutine? Yield control so other ready tasks can run.
Python 3.15: What is fractions.Fraction(6, 8)? Fraction(3, 4), reduced to lowest terms.
Python 3.15: What does asyncio.wait_for normally do to its awaited task on timeout? It cancels the task and raises TimeoutError; waiting for cancellation cleanup may exceed the nominal timeout.
Python 3.15: Does typing.Final prevent assignment at runtime by itself? No. It communicates reassignment restrictions to type checkers.
Python 3.15: Why protect a shared read-modify-write operation with a threading.Lock rather than relying on the GIL? The operation is not guaranteed to be atomic; free-threaded builds also do not provide GIL-based serialization.
Python 3.15: Does PurePath.is_relative_to prove that a path stays inside a directory after resolving symlinks? No. It is a lexical path test, not a filesystem containment check.
Python 3.15: After s = io.StringIO('abc') and s.read(1), what does the next s.read() return? 'bc'; the stream position advanced past the first character.
Python 3.15: Does Fraction(0.1) necessarily equal Fraction(1, 10)? No. Converting the float preserves its exact binary floating-point value.
Python 3.15: What does queue.Queue.get() do by default when the queue is empty? It blocks until an item is available, unless interrupted by an applicable shutdown or exception.
Python 3.15: Do pickle.dumps and pickle.loads serialize to and consume a text string format? No. Pickle uses a binary byte-stream representation.
Python 3.15: Which time clock is appropriate for elapsed deadlines because it cannot go backward with wall-clock adjustments? time.monotonic().
Python 3.15: What is pathlib.PurePosixPath('/srv/report.csv').name? The string 'report.csv', containing the final path component.
Python 3.15: What static-checking behavior distinguishes typing.Any from object? Any permits unchecked operations and compatibility with other types; object still requires operations valid for an arbitrary object.
Python 3.15: What extra filesystem work does Path.resolve perform compared with merely joining path components? It makes the path absolute and resolves symbolic links and '..' components.
Python 3.15: Does secrets.token_urlsafe(16) promise a token of exactly 16 text characters? No. 16 specifies random bytes before URL-safe Base64 encoding.
Python 3.15: Does asyncio.gather return successful results in completion order or argument order? Argument order.
Python 3.15: What does contextlib.aclosing(obj) await on async context exit? obj.aclose().
Python 3.15: Does shutil.copyfile preserve a source file's permission bits and timestamps? No. It copies file contents; use copy2 for an attempt to preserve metadata too.
Python 3.15: Which fields participate in generated dataclass equality by default? All fields marked compare=True, which is the default.
Python 3.15: What exception does sys.exit raise rather than forcibly terminating all code immediately? SystemExit; normal exception unwinding still runs applicable finally blocks.
Python 3.15: What is struct.calcsize('!I')? 4 bytes.
Python 3.15: How do you obtain an aware current UTC datetime without using deprecated utcnow()? datetime.datetime.now(datetime.UTC).
Python 3.15: Which datetime method converts an aware timestamp to another time zone while preserving the instant? dt.astimezone(target_zone).
Python 3.15: With autocommit=False, which method discards pending transaction changes? connection.rollback().
Python 3.15: What kind of identifier does zoneinfo.ZoneInfo('Europe/Paris') use? An IANA time-zone key, whose rules can include daylight-saving changes.
Python 3.15: Why does deepcopy keep a memo dictionary during a copy operation? It handles recursive structures and avoids repeatedly copying the same encountered object.
Python 3.15: What does secrets.token_bytes(16) return? 16 cryptographically strong random bytes.
Python 3.15: Which json function parses a JSON string into Python objects? json.loads(text).
Python 3.15: What does an asyncio.TaskGroup context do before normal exit? It waits for all tasks created within the group to finish.
Python 3.15: Which random function samples a list of k elements with replacement and can use weights? random.choices(population, weights=..., k=k).
Python 3.15: With shell=False, does subprocess.run(['echo', '*.csv']) ask a shell to expand the wildcard? No. '*.csv' is passed as a literal argument.
Python 3.15: What type does ZipFile.read('notes.txt') return? bytes, even if the member contains text.
Python 3.15: Which enum decorator rejects duplicate member values rather than accepting aliases? @enum.unique.
Python 3.15: Which Path.mkdir options create missing parent directories and tolerate an existing directory? parents=True and exist_ok=True; an existing non-directory can still cause an error.
Python 3.15: Which datetime class method parses '2026-04-09' into a date? datetime.date.fromisoformat('2026-04-09').
Python 3.15: What is collections.Counter('aba')['a']? 2.
Python 3.15: How can logger.error include the current exception traceback? Pass exc_info=True while handling the exception.
Python 3.15: What does csv.DictReader use as field names when fieldnames is not supplied? The first row of the input, which is then omitted from the data rows.
Python 3.15: How does socket.sendall differ from send for a byte string? sendall keeps sending until all data is sent or an error occurs; send may write only part of it.
Python 3.15: What is list(itertools.zip_longest([1, 2], ['a'], fillvalue=None))? [(1, 'a'), (2, None)].
Python 3.15: Which logging component sends a record to a destination such as a file or stream? A Handler.
Python 3.15: Is urllib.error.HTTPError also a kind of URLError? Yes. Catch HTTPError first if it needs separate handling.
Python 3.15: What must a consumer call once for each retrieved item when using a queue.Queue instance q with q.join for completion tracking? q.task_done() after finishing that item's work.
Python 3.15: Which Logger method logs an error and includes the active exception traceback by default? logger.exception(...), normally called inside an except block.
Python 3.15: What does cursor.executemany(sql, rows) do with parameterized DML? It executes the statement repeatedly with each supplied parameter set.
Python 3.15: Which deque method removes and returns the leftmost element? popleft().
Python 3.15: Can a keyword passed when calling a partial override a keyword stored in that partial? Yes. Call-time keyword arguments take precedence.
Python 3.15: Why does Decimal('0.1') better express an exact decimal tenth than Decimal(0.1)? The string specifies the decimal value directly; the float version preserves the float's binary approximation.
Python 3.15: Which argument's type determines dispatch for functools.singledispatch? The first positional argument's type.
Python 3.15: What does subprocess.run(..., check=True) do when the child returns a nonzero status? It raises subprocess.CalledProcessError.
Python 3.15: What does typing.Annotated[int, 'positive'] add to int? Metadata for tools; Python does not automatically enforce positivity.
Python 3.15: Which math predicate tests whether a float is NaN? math.isnan(value). Comparing NaN to itself with == is false.
Python 3.15: What does doctest test in documentation strings? Interactive Python examples and their expected displayed output.
Python 3.15: What does ThreadPoolExecutor.submit(fn, *args) return immediately? A Future representing the submitted call; it may already be complete.
Python 3.15: What does urllib.parse.urlencode({'q': 'red blue'}) produce? 'q=red+blue'.
Python 3.15: Which re function yields match objects lazily for non-overlapping matches? re.finditer(pattern, text).
Python 3.15: Which ZipFile method returns a list of member names? namelist().
Python 3.15: What does operator.attrgetter('real')(3 + 4j) return? 3.0, the object's real attribute.
Python 3.15: What type does urllib.request.urlopen(...).read() normally return? bytes; decode using the response's appropriate character encoding when text is needed.
Python 3.15: How does re.search differ from re.prefixmatch in where it looks for a match? search scans anywhere; prefixmatch starts at the beginning. prefixmatch was added in 3.15 as the preferred name for the older match API.
Python 3.15: Which unittest.TestCase assertion compares values for equality and reports useful differences? assertEqual(actual, expected).
Python 3.15: Which add_argument parameter supplies a value when an optional argument is absent? The default parameter.
Python 3.15: How do you open a gzip-compressed file for UTF-8 text reading? gzip.open(path, 'rt', encoding='utf-8').
Python 3.15: Which dataclass hook is called after the generated __init__ assigns the fields? __post_init__().
Python 3.15: Do ordinary Python type annotations automatically reject arguments of the wrong type at runtime? No. Type hints primarily support static checking and tooling; runtime validation must be implemented separately.
Python 3.15: What does HMAC add to an ordinary hash for message authentication? A secret key shared by the parties creating and verifying the authentication tag.
Python 3.15: What operation does an Iterator provide in addition to being iterable? __next__(), which produces the next item or raises StopIteration.
Python 3.15: Which asyncio helper can run a blocking I/O function in a worker thread? await asyncio.to_thread(fn, *args).
Python 3.15: What does operator.methodcaller('replace', 'a', 'x')('banana') return? 'bxnxnx'.
Python 3.15: Which contextlib helper can stand in for a with block when no resource management is needed? contextlib.nullcontext(), optionally carrying an enter_result.
Python 3.15: Which file-opening mode appends text without truncating existing contents? 'a'; use an explicit text encoding when appropriate.
Python 3.15: What relationship can a single TypeVar express in a function's input and return annotations? That the chosen input type and return type are linked, rather than independently arbitrary.
Python 3.15: Why is validating member paths alone insufficient when processing an untrusted archive? Its contents can still consume excessive storage, memory or processing time.
Python 3.15: Does textwrap.fill return a list of lines or a single string? A single string containing wrapped lines separated by newline characters.
Python 3.15: What commonly written method does @dataclass generate from annotated instance fields by default? __init__, along with other configured methods such as __repr__ and __eq__.
Python 3.15: What does traceback.format_exc return while handling an exception? A formatted traceback string for the currently handled exception.
Python 3.15: What does contextlib.closing(obj) call on context exit? obj.close().
Python 3.15: Does itertools.count(5) stop after a fixed number of values? No. It is unbounded unless the consumer stops taking values.
Python 3.15: Which Mock method verifies one call with specified arguments and no additional calls? assert_called_once_with(...).
Python 3.15: Does Base64 encode data confidentially? No. It is a reversible binary-to-text encoding, not encryption.
Python 3.15: Which operator function returns the truth value of an object as a bool? operator.truth(obj).
Python 3.15: Which method clears an lru_cache-decorated function's stored results? cached_function.cache_clear().
Python 3.15: What constraint does lru_cache place on arguments used as cache keys? They must be hashable.
Python 3.15: Which math.isclose tolerance is usually needed when comparing a tiny value with zero? A suitable abs_tol; relative tolerance alone does not make a nonzero value close to zero.
Python 3.15: What usually happens to sibling tasks when a TaskGroup child raises a non-cancellation exception? They are cancelled; after cleanup, failures are raised together in an exception group.
Python 3.15: Which subprocess.run option captures both stdout and stderr separately? capture_output=True.
Python 3.15: Where does assigning cm['x'] = 4 store the value in a ChainMap? In the first mapping only.
Python 3.15: Can a SHA-256 digest be decrypted with a key to recover the original data? No. A hash is not reversible encryption.
Python 3.15: After a = [[1]] and b = copy.deepcopy(a), does b[0].append(2) change a[0]? No. The nested list was copied as well.
Python 3.15: Which asyncio context manager limits how long a block of async work may take? asyncio.timeout(delay), used with async with.
Python 3.15: Which asyncio function schedules a coroutine as a Task on the running loop? asyncio.create_task(coro).
Python 3.15: How can argparse convert --count to an integer during parsing? parser.add_argument('--count', type=int).
Python 3.15: Does urllib.parse.urlsplit guarantee that a parsed URL is safe or semantically valid for an application? No. The application must validate the components it intends to trust.
Python 3.15: Which pathlib class family performs lexical path manipulation without filesystem access? PurePath and its platform-specific subclasses, PurePosixPath and PureWindowsPath.
Python 3.15: Does @dataclass(frozen=True) make nested mutable objects deeply immutable? No. It blocks normal field assignment, but nested mutable values can still change.
Python 3.15: How does dataclasses.replace(obj, x=3) affect obj? It constructs a new instance with the changed field; the original is unchanged.
Python 3.15: What is pathlib.PurePosixPath('backup.tar.gz').suffixes? The list ['.tar', '.gz'].
Python 3.15: What is list(itertools.repeat('x', 3))? ['x', 'x', 'x'].
Python 3.15: Which itertools tool lazily flattens a stream of iterables by one level? itertools.chain.from_iterable(iterables).
Python 3.15: Does ExitStack.pop_all immediately execute the registered cleanup callbacks? No. It transfers them to a new ExitStack, which owns the remaining cleanup.
Python 3.15: How can tar.extractall explicitly request the data extraction filter? Pass filter='data'.
Python 3.15: Which sys attribute normally gives the absolute path of the running Python interpreter? sys.executable; it can be empty or None if Python cannot determine it.
Python 3.15: What happens to an existing file when Path.write_text writes new text to it? Its contents are overwritten, not appended.
Python 3.15: What types must keys and values assigned to os.environ have? They must be strings.
Python 3.15: Which standard stream should a command-line tool normally use for diagnostics kept separate from its normal output? sys.stderr.
Python 3.15: What can create_autospec catch that an unrestricted Mock may accept? Calls incompatible with the real object's signature or attributes.
Python 3.15: Why use await asyncio.sleep(delay) instead of time.sleep(delay) inside an async task? It suspends the task without blocking the event-loop thread.
Python 3.15: What resource-management benefit does using TemporaryFile as a context manager provide? The file is closed and normally removed when the context exits.
Python 3.15: Why can itertools.tee require substantial memory when one consumer runs far ahead? It buffers values until the slower copies consume them.
Python 3.15: How can pathlib.Path read a UTF-8 text file with an explicit encoding? Call path.read_text(encoding='utf-8').
Python 3.15: Is asyncio.Lock intended to synchronize operating-system threads? No. It coordinates asyncio tasks and is not thread-safe.
Python 3.15: Which contextlib class manages a dynamically determined number of synchronous context managers? ExitStack.
Python 3.15: What does leaving a unittest.mock.patch context do to the patched name? It restores the original object, including when the block raises.
Python 3.15: Why should csv.writer be used instead of joining fields with commas? It handles delimiters, quotes and embedded newlines according to the CSV dialect.
Python 3.15: Which re function requires the entire string to match a pattern? re.fullmatch(pattern, text).
Python 3.15: What is math.isqrt(20)? 4, the floor of the exact square root.
Python 3.15: What does typing.Callable[[str], int] describe? A callable accepting a string argument and returning an integer.
Python 3.15: When does a TestCase's setUp run? Before each test method, not just once for the whole class.
Python 3.15: Does decimal context precision count fractional places or significant digits in arithmetic results? Significant digits, not a fixed number of fractional places.
Python 3.15: What is list(itertools.chain([1, 2], [3]))? [1, 2, 3].
Python 3.15: What does @abc.abstractmethod prevent when applied in an ABC with unimplemented abstract methods? Instantiating a subclass that has not implemented all required abstract methods.
Python 3.15: What does math.isfinite(float('inf')) return? False; infinities and NaNs are not finite.
Python 3.15: What is list(itertools.product([1, 2], ['x']))? [(1, 'x'), (2, 'x')].
Python 3.15: Which pathlib call searches below a directory for matching .csv paths recursively? path.rglob('*.csv'). It yields matches lazily; check is_file() if only files are wanted.
Python 3.15: Why use zipfile.ZipFile in a with block when creating an archive? It ensures the archive is closed and essential directory records are written.
Python 3.15: How many hexadecimal characters does a SHA-256 hexdigest contain? 64.
Python 3.15: Does the env argument to subprocess.run automatically merge its mapping with the parent's environment? No. It supplies the child's environment mapping; merge with os.environ explicitly if needed.
Python 3.15: Does updating a hash with b'ab' then b'cd' match hashing b'abcd' at once? Yes. update calls append bytes to the same logical input stream.
Python 3.15: Which DictWriter method writes its configured field names as a header row? writeheader().
Python 3.15: How can subprocess.run decode captured output explicitly as UTF-8 text? Pass encoding='utf-8', which also enables text mode.
Python 3.15: What does maxsize=128 limit in functools.lru_cache? The number of recently used argument-result entries retained.
Python 3.15: Which urlsplit result attribute contains the path without the query string? path.
Python 3.15: Which os function returns the current working directory as a string? os.getcwd().
Python 3.15: Can a function registered with ExitStack.callback suppress an exception by returning True? No. That callback is not passed the exception details and its return value does not suppress it.
Python 3.15: What distinguishes uuid.uuid4 from a name-based UUID? It creates a random UUID rather than deriving it from a namespace and name.
Python 3.15: Does defaultdict.get('missing') invoke the default factory? No. The factory is invoked by missing-key [] access, not get().
Python 3.15: What does list(itertools.batched([1, 2, 3, 4, 5], 2)) return by default? [(1, 2), (3, 4), (5,)].
Python 3.15: What Python type does json.dumps({'x': 1}) return? str, not bytes.
Python 3.15: After a = [[1]] and b = copy.copy(a), are a[0] and b[0] the same list? Yes. A shallow copy creates a new outer container while sharing nested objects.
Python 3.15: How many times must a generator decorated with contextlib.contextmanager yield in normal use? Exactly once: setup precedes the yield and cleanup follows it.
Python 3.15: What does arcname control in ZipFile.write(filename, arcname=...)? The member name stored inside the archive, independently of the source filesystem path.
Python 3.15: What logging call conventionally creates a logger named after the current module? logging.getLogger(__name__).
Python 3.15: Which json.dumps option rejects NaN and infinity rather than emitting nonstandard JSON tokens? allow_nan=False.
Python 3.15: What does contextlib.ContextDecorator let a context manager do for an ordinary synchronous function in addition to supporting with? Wrap the function as a decorator, applying the context around each call.
Python 3.15: Which os operation replaces a destination path with a source path, atomically if the rename succeeds? os.replace(src, dst); moving across filesystems can fail.
Python 3.15: What is math.floor(-2.7)? -3.
Python 3.15: What does typing.Literal['read', 'write'] express to a type checker? A value restricted to the two specified string literals.
Python 3.15: Does a class have to inherit from a Protocol to satisfy its static interface? No. Structural typing checks whether the required members are present with compatible types.
Python 3.15: Which method-name prefix does unittest's default loader recognize as a test? test.
Python 3.15: Which open mode fails if the target file already exists? 'x' for exclusive text creation, or 'xb' for binary creation.
Python 3.15: After f = functools.partial(pow, 2), what does f(5) return? 32; the first argument to pow is fixed at 2.
Python 3.15: Which time function provides a high-resolution performance counter for measuring short elapsed intervals? time.perf_counter(); subtract two readings rather than interpreting one as a calendar time.
Python 3.15: For an Enum member Color.RED, which attribute gives its declared name as a string? Color.RED.name.
Python 3.15: What does Counter('abb').most_common(1) return? [('b', 2)].
Python 3.15: What is pathlib.PurePosixPath('backup.tar.gz').stem? The string 'backup.tar'; only the final suffix is removed.
Python 3.15: Which ArgumentParser method adds support for commands such as 'build' and 'clean'? add_subparsers(), followed by add_parser() for each subcommand.
Python 3.15: What does itertools.batched(data, 3, strict=True) do when the final batch is incomplete? It raises ValueError when that incomplete batch is reached.
Python 3.15: Which io class provides an in-memory binary stream? io.BytesIO.
Python 3.15: Which mapping supplies a key that appears in several maps of a ChainMap? The first mapping containing the key.
Python 3.15: How do you retrieve the Color member named 'RED'? Color['RED'].
Python 3.15: Which CompletedProcess attribute contains the child process's exit status? returncode.
Python 3.15: Why use Popen.communicate rather than independently reading one pipe while the child also writes heavily to another? communicate handles the streams together, avoiding the common full-pipe deadlock pattern.
Python 3.15: What is math.ceil(-2.7)? -2.
Python 3.15: What sequence should accompany execute('SELECT ?', ...) to bind the string 'Ada' as one value? ('Ada',), with the trailing comma that makes a one-element tuple.
Python 3.15: Does warnings.warn always interrupt execution like raising an exception? No. Warning filters control whether it is shown, ignored or converted into an exception.
Python 3.15: What is statistics.median([1, 3, 7, 9])? 5.0, the mean of the two central values.