80 questions / 10 random questions
Random questions, instant feedback, and review for missed questions.
View recommended Practical Python Basics resources →
Which type stores an ordered, mutable collection whose items can be added or removed?
Answer: list
A list is an ordered, mutable collection.
Which data structure is appropriate for looking up a name by user ID?
Answer: dict
A dict maps keys to values and supports key-based lookup.
Which type is appropriate for a collection of unique tags?
Answer: set
A set represents a collection of unique elements.
How can you get a default value when a dictionary key is missing without raising an exception?
Answer: mapping.get(key, default)
dict.get returns the supplied default when the key is absent.
How should you process many values lazily without keeping them all in memory?
Answer: A generator using yield
A generator produces values on demand and can reduce memory usage.
What problem can occur when an empty list is used directly as a function default argument?
Answer: The same list is reused across calls
Default arguments are evaluated at definition time; use None and create the list inside.
Which syntax collects variable positional arguments in a function?
Answer: *args
*args receives extra positional arguments as a tuple.
Which construct ensures a resource is released whether or not an exception occurs?
Answer: Use a context manager with a with statement
with reliably invokes a context manager's cleanup.
How should you handle only an expected exception without hiding other failures?
Answer: Catch a specific exception such as ValueError
Catching specific exceptions lets unexpected failures propagate.
How can you add domain context to an exception while preserving the original cause?
Answer: raise NewError(...) from exc
raise ... from ... explicitly chains exceptions and preserves causality.
What is a readable way to interpolate variables into a string?
Answer: An f-string
An f-string embeds expressions clearly and readably.
What happens when a non-string value is concatenated directly to a string with +?
Answer: It commonly raises TypeError
Convert explicitly with str or use an f-string.
Which operator normally compares whether two variables have equal values?
Answer: ==
== compares value equality, while is checks object identity.
What is the recommended way to test whether a value is None?
Answer: value is None
None is a singleton, so use identity comparison with is.
How should you loop over a sequence with both index and value?
Answer: enumerate(sequence)
enumerate returns an index and item together.
How do you parse a JSON string into Pythonオブジェクトs?
Answer: json.loads(text)
json.loads decodes JSON text into dicts, lists, and other values.
How do you serialize a Pythonオブジェクト to a JSON string?
Answer: json.dumps(value)
json.dumps encodes supported objects as JSON text.
How should you reliably open a UTF-8 text file for reading?
Answer: open(path, encoding="utf-8")
Specifying encoding avoids platform-default differences.
Which API supports portable filesystem path operations?
Answer: pathlib.Path
pathlib handles path joining, inspection, and I/O portably.
What is a safe basic approach for running an external command with arguments?
Answer: Pass an argument list to subprocess.run and keep shell=False
An argument list with shell=False reduces shell-injection risk.
What is the basic way to isolate dependencies per project?
Answer: Create a virtual environment with venv or a similar tool
A virtual environment isolates a project's interpreter environment and packages.
How should you make application dependency versions reproducible?
Answer: Version-control locked dependencies and install the same set in CI
Locked dependencies reduce unexpected version differences between environments.
Which guard runs CLI code only when a module is executed directly?
Answer: if __name__ == "__main__":
When run directly, __name__ is __main__, avoiding import-time side effects.
What is a basic way to read configuration from the environment instead of hard-coding it?
Answer: Read environment variables via os.environ or a configuration library
Environment variables separate configuration from code; combine them with validation and secret storage.
Which standard module provides levels, timestamps, and configurable destinations for application logs?
Answer: logging
logging supports levels, formatters, and handlers for operational logs.
When processing many records, one bad record should not always abort the whole batch. What is appropriate?
Answer: Catch failures per record, log them, and continue, retry, or quarantine by policy
Clear failure boundaries and retry policy support partial-failure handling.
What is a sound basic policy for network failures in an HTTP API call?
Answer: Set timeouts and retry only retryable failures with backoff
Timeouts and selective retries prevent hangs and overload.
What should you use to document function input and return types for static checking?
Answer: Type hints
Type hints are not runtime enforcement, but IDEs and type checkers can detect mismatches.
What is appropriate for a simple data container that needs generated init and repr methods?
Answer: @dataclass
A dataclass can generate init, repr, and comparisons from fields.
What is the safe way to pass user input into a database query?
Answer: Use the database driver's パラメータ化クエリ
Parameter binding separates values from SQL syntax and prevents SQL injection.
What is appropriate for automatically verifying expected output from a small function?
Answer: Write a unit test asserting inputs and expected outputs
A unit test checks small behavior quickly and repeatedly.
How should you keep a unit test stable for code that calls an external API?
Answer: Inject the dependency and replace the boundary with a mock or fake
Replacing external boundaries keeps tests fast and deterministic while integration tests cover real connections.
How should a test avoid leaking temporary files?
Answer: Use a temporary-directory fixture or context manager
Let the test framework or context manager own temporary-resource cleanup.
What is the problem with using assert as the only production input validation?
Answer: Assertions can be disabled by optimization options
assert is for development invariants; use explicit exceptions for input errors.
Why should pickle be avoided for untrusted data?
Answer: Deserialization can lead to arbitrary code execution
pickle is for trusted Pythonオブジェクトs; external input needs safer formats and schema validation.
What is the problem with passing untrusted text to eval?
Answer: It can execute arbitrary Python code
eval executes text as code; use a parser or explicit conversion instead.
What is a common choice for parallelizing CPU-bound pure Python work across cores?
Answer: multiprocessing or a process pool
Processes use separate interpreters and can distribute CPU-bound work across cores.
Which option can efficiently handle many I/O-waiting tasks?
Answer: asyncio with async-compatible libraries
asyncio can run other tasks while I/O waits, but blocking work must be avoided.
Which information is useful in logs for production incident analysis?
Answer: Record time, level, request or ジョブID, and key context without secrets
Correlation IDs and context improve traceability while secrets and personal data must be minimized.
Why is calling sys.exit inside a reusable library function often problematic?
Answer: The caller loses control over error handling and cleanup
Libraries should raise meaningful exceptions and let a CLI or boundary decide whether to exit.
How should you sort users by ascending age and then by ascending name for equal ages?
Answer: sorted(users, key=lambda u: (u.age, u.name))
Key tuples are compared from left to right, so they clearly express multi-field ordering. sorted does not mutate the original list.
After copying a nested dict with copy.copy(), changing an inner list also changes the original. What explains this and how can it be addressed?
Answer: A shallow copy shares nested objects; use copy.deepcopy or an explicit independent copy when required
A shallow copy creates a new outer container but shares references to nested values. Consider deepcopy cost and objects that should remain shared.
How should a dataclass field be defined so each instance receives its own empty list?
Answer: field(default_factory=list)
default_factory creates a new list for each instance and avoids sharing a mutable default.
Which choice is appropriate for monetary totals that should avoid binary floating-point artifacts such as 0.1 + 0.2?
Answer: Create decimal.Decimal values from strings and specify the required rounding rule
Decimal controls decimal precision and rounding. Construct it from strings or integer minor units rather than importing an existing binary float artifact.
What is a safe policy for storing and comparing timestamps in an API serving users in multiple time zones?
Answer: Store and compare timezone-aware UTC datetimes, converting to the user's time zone for display
UTC-aware datetimes represent instants unambiguously. Define input and output zones and ISO 8601 formats, then convert at display boundaries.
How should a UTF-8 CSV file be opened with the standard csv module to avoid extra blank lines, including on Windows?
Answer: open(path, mode, encoding='utf-8', newline='')
Use newline='' so the csv module controls newline handling and specify the encoding explicitly. Choose utf-8-sig only when an external format requires a BOM.
How should a configuration file be updated so readers do not see a partially written file if the process stops?
Answer: Write the complete content to a temporary file on the same filesystem, flush as required, then replace with os.replace
Completing a temporary file and replacing within the same filesystem helps readers observe either the old or new version. Consider fsync and backups for stronger durability requirements.
Which standard-library choice consistently handles required CLI options, type conversion, help messages, and exit codes?
Answer: argparse
argparse handles definitions, parsing, type conversion, usage and help, and invalid-input exits. Separating CLI boundaries from business logic also improves testability.
Which file is central to the standard format for build-system settings, project metadata, and core dependencies in a modern Pythonプロジェクト?
Answer: pyproject.toml
pyproject.toml is the standard location for build backends, project metadata, dependencies, and tool configuration. Lock-file handling depends on the package manager.
Which standard-library approach is appropriate for generating a hard-to-guess password-reset token?
Answer: secrets.token_urlsafe()
The secrets module generates cryptographically strong randomness for authentication tokens. Also design sufficient entropy, expiration, and single use.
What is the appropriate basic policy for storing application passwords?
Answer: Use a trusted library implementing a salted, slow password hash such as Argon2
Password storage needs a dedicated KDF that slows brute force and a per-password salt. Plan parameter upgrades and rehashing as well.
How should several database updates be handled so they commit only if all succeed and roll back when an exception occurs?
Answer: Use the driver or ORM transaction context to commit on success and roll back on exception
Define the transaction boundary and reliably manage commit, rollback, and connection return through a context manager. Avoid holding locks across slow external calls.
What is required to retrieve all records from an HTTP API that uses page tokens?
Answer: Follow each response's next token until termination, accounting for rate limits and possible duplicates
Follow the pagination contract until no next token remains. Design timeouts, errors, rate limits, deduplication, and checkpoints as required.
How should a multi-gigabyte HTTP response be saved to a file while keeping memory use bounded?
Answer: Receive the response in streaming mode and write bounded chunks to the file
Streaming chunked writes keep memory bounded. Combine them with timeouts, status checks, size limits, temporary files, checksums, and failure cleanup.
Which conditions make functools.lru_cache appropriate for an expensive function?
Answer: The same hashable arguments produce the same acceptable result, staleness is understood, and maxsize is considered
lru_cache reuses results keyed by arguments. Consider purity, hashability, freshness, memory bounds, and when cache_clear is needed.
How can pytest test the same function with many input and expected-value pairs while reducing duplicated test code?
Answer: List the cases with @pytest.mark.parametrize
Parametrize supplies multiple cases to one test body and reports each case separately, making boundary and error cases easy to add.
How should a pytest fixture create a test database connection and guarantee rollback and close even when the test fails?
Answer: Create the resource in a fixture, yield it, and perform cleanup after yield with finally-style guarantees
A yield fixture expresses setup before yield and teardown afterward, allowing cleanup on test success or failure. Choose scope while preserving test isolation.
How can an external service client be replaceable and type-checked by required methods without requiring inheritance from a specific class?
Answer: Define the required interface with typing.Protocol
Protocol structurally accepts types that provide the required attributes and methods, keeping implementations decoupled and fakes or adapters statically checkable.
Multiple threads perform read-modify-write operations on a shared dict and updates are lost. What is a basic remedy?
Answer: Reduce shared state and protect required critical sections with threading.Lock or an appropriate synchronization primitive
Read-modify-write consists of multiple operations and can race. Choose locks, queues, thread-local state, or immutable data as appropriate, and consider lock scope and deadlocks.
How should a containerized Pythonワーカー handle SIGTERM so it can finish in-flight work and exit safely?
Answer: Have the signal handler set a shutdown flag, stop accepting new work, and let the main loop clean up and exit within the deadline
Keep the signal handler small and communicate shutdown to normal control flow. Design queue intake, in-flight work, checkpoints, connection closing, and the platform grace period.
An API returns records through a generator. After iterating over it to count records, passing the same generator to a save routine yields no records. Why?
Answer: A generator is consumed by iteration and does not restart automatically
A generator retains iteration state and remains exhausted after reaching the end. Save and count in one pass, recreate the source, or materialize records only when memory requirements allow.
FEATURE_ENABLED contains the string 'false', but bool(value) enables the feature. How should this configuration be handled?
Answer: Parse an explicit set of true and false strings and reject unknown values
Nonempty strings are truthy, including 'false'. Define explicit accepted values such as true and false, along with a default for missing configuration and an error policy for invalid values.
On Python 3.10 or later, product IDs and prices are paired using zip. How can a length mismatch be detected when the pairs are fully consumed?
Answer: Use zip with strict=True and handle ValueError for unequal lengths
Ordinary zip stops at the shortest input. With strict=True, consuming unequal inputs raises ValueError. Earlier pairs can already have been yielded, so separate validation from writes when atomic processing is required.
Sales rows with customer IDs A, B, A produce two A groups with itertools.groupby. How should you make one group per customer?
Answer: Sort rows by customer ID, then groupby using that same customer ID
groupby groups consecutive equal keys, not all matching rows throughout the input. Sort by the grouping key first, or accumulate totals in a dictionary. Consider sorting costs for large inputs.
orders.py imports a function with 'from gateway import charge'. Which patch target replaces the payment call looked up inside orders during a test?
Answer: Patch orders.charge, replacing the name looked up by the calling module
Patch where the code under test looks up the name. A from-import binds charge in orders; later replacing gateway.charge does not update that existing binding.
The number of input files is determined at runtime. How can you close all previously opened files if opening a later file fails?
Answer: Register each opened file with ExitStack for cleanup on scope exit
Within a with ExitStack() block, enter_context(open(...)) registers cleanup as each acquisition succeeds. If a later acquisition fails, previously registered files are closed in reverse order.
Threads use queue.Queue. join still blocks after workers have retrieved every item with get. How should workers signal that retrieved work is finished?
Answer: Call task_done exactly once for each get when processing has finished
join waits for the unfinished-task count to reach zero, not merely for an empty queue. get does not decrement that count; task_done does. Handle retries or record failures before reliably acknowledging completion.
In an asyncio application, a synchronous external SDK blocks other tasks while waiting for I/O. What can you do when an async SDK replacement is not yet available?
Answer: Check thread safety and invoke the SDK through await asyncio.to_thread
Blocking I/O still blocks inside async def. to_thread runs a synchronous function in a separate thread and lets the event loop await it. Check SDK thread safety, bound concurrency, and configure the SDK's own I/O timeout.
You need a sorted copy while preserving the original list, but result = items.sort() produces None. Which correction fits?
Answer: Use result = sorted(items) to obtain a separate sorted list
list.sort mutates its list and returns None. sorted creates a new list, but not a deep copy of its elements; mutable elements can still be shared with the original.
A CSV decoded as UTF-8 with errors='ignore' silently loses characters from customer names. Which policy prevents unnoticed data loss?
Answer: Decode strictly, detect failures, and quarantine or reacquire data after checking its encoding
errors='ignore' silently discards undecodable bytes. Follow the input encoding contract and use strict decoding to detect violations. Protect failed input and avoid logging sensitive contents while arranging correction or reacquisition.
Which Python clock should measure elapsed time without going backward when the system clock is corrected?
Answer: Use the difference between time.monotonic readings
monotonic does not go backward; use differences between readings. Use wall-clock timestamps for event dates, not as a substitute for duration measurement across clock corrections.
Which json.dumps setting rejects NaN instead of emitting a nonstandard value for an external API?
Answer: Set allow_nan=False
allow_nan=False raises ValueError for NaN or infinities. Decide explicitly whether invalid numeric data should be rejected or represented as missing according to the API contract.
A caller appends to a list returned by an lru_cache function. Why does the next call with the same argument see the added item?
Answer: The cached result is the same mutable list
lru_cache retains and reuses result objects. Mutating a cached list affects later callers. Prefer immutable results or explicitly copy at an appropriate boundary.
What happens to obj.tags.append('x') when tags is a list field in a frozen Python dataclass?
Answer: The nested list can mutate and receives the item
Frozen dataclasses block ordinary attribute assignment, not mutation of nested objects. Rebinding tags differs from appending to the list. Use suitable immutable field types when needed.
Which subprocess.run option raises an exception when a command exits with code 2?
Answer: Use check=True for the run call
check=True raises CalledProcessError for nonzero exit status. Output capture and text decoding do not check success. Handle launch failures and timeouts separately.
Which quantize rounding mode rounds Decimal('2.345') to two decimal places, breaking ties away from zero?
Answer: Use ROUND_HALF_UP, producing 2.35
Quantize with Decimal('0.01') and ROUND_HALF_UP to get 2.35. HALF_EVEN instead chooses an even final digit. Specify the business rule and avoid importing binary-float artifacts.
For shared=[] and source=[shared, shared], what happens when copy.deepcopy(source) is called once on these ordinary lists?
Answer: They share one copied list independent of the original
Within one copy operation, deepcopy uses a memo to preserve repeated references. Both copied elements reference one new list, separate from the original shared list.
How does the default csv.reader preserve a customer code such as 00123?
Answer: Return text without numeric conversion
The default csv.reader returns strings. Keep identifiers as text rather than converting them to numbers. Options such as QUOTE_NONNUMERIC or later conversion can change that behavior.
Which Python pattern cleans up a temporary working directory and its contents on ordinary scope exit, including exceptions?
Answer: Use with tempfile.TemporaryDirectory()
TemporaryDirectory provides context-managed cleanup; mkdtemp requires manual removal. Close open files and handle cleanup errors. Abrupt process termination is not covered by ordinary context exit.
Which Python standard function reduces timing leakage when comparing a supplied token with an expected value?
Answer: Use secrets.compare_digest for comparison
compare_digest avoids content-based short-circuit comparison. Use compatible same-type inputs; it does not hide all length or type information or replace token expiry and replay controls.