Browse Chunks

Showing 5201-5250 of 7392 chunks

with ThreadPoolExecutor() as executor: futures =
CAT_5

Submits multiple callable tasks to a managed pool of reusable threads, collecting Future objects that represent each pending computation. Addresses the overhead and error-prone complexity of manually creating, starting, and joining individual threads for parallel I/O-bound work. Reached for when you need to run many independent tasks concurrently without blocking the main thread on each one sequentially.

with ThreadPoolExecutor(max_workers=num_workers) as executor: futures = [executor.submit(func, arg) for arg in iterable]

executor.submit(task_func, *args, **kwargs).add_done_callback
CAT_5

Submits a callable to an Executor for asynchronous execution and registers a callback to be invoked when the resulting Future completes.

executor.submit(task_func, *args, **kwargs).add_done_callback(callback)

concurrent.futures.wait
CAT_5

Waits for a set of Future objects to complete, optionally with a timeout and a condition for when to return (e.g., when the first future completes). Returns two sets: done and not_done futures.

concurrent.futures.wait(futures, timeout=timeout, return_when=return_when)

[result for result in executor.map(task_func, iterable, chunksize=100)]
CAT_5

Applies a function to each item in an iterable in parallel using an executor, collecting results into a list with a chunk size of 100 for batching.

[result for result in executor.map(task_func, iterable, chunksize=100)]

with ThreadPoolExecutor(initializer=init_worker, initargs=(shared,)) as executor:
CAT_5

Creates a ThreadPoolExecutor where each worker thread is initialized with a shared object via the init_worker function before processing any tasks.

with ThreadPoolExecutor(initializer=<callable>, initargs=(<args>,)) as <executor>:

@my_decorator def greet(): return 'Hello'
CAT_6

Applies a decorator to modify or extend the behavior of the greet function.

@<decorator_name> def <function_name>(<parameters>): <body>

def repeat(times): def decorator(func): def wrapper(*args, **kwargs): for _ in range(times): func(*args, **kwargs) return wrapper return decorator
CAT_6

A parameterized decorator that executes the decorated function a specified number of times, useful for repeating side‑effects or retry‑like behavior without writing explicit loops.

def repeat(;): def decorator(;): def wrapper(*args, **kwargs): for _ in range(;): ;(*args, **kwargs) return wrapper return decorator

@staticmethod\ndef utility():\n return 42
CAT_6

A static utility method that returns the constant integer 42, often used as a placeholder or example value.

@staticmethod\ndef <method_name>():\n return <literal>

@classmethod\\ndef create(cls):\\n return cls()
CAT_6

Defines a class method named create that returns a new instance of the class, serving as an alternative constructor.

@classmethod\n\ndef create(cls):\n return cls()

@classmethod def from_dict(cls, data): return cls(**data)
CAT_6

Creates a new instance of a class by unpacking a dictionary's key-value pairs as keyword arguments into the class constructor. Solves the problem of manually mapping dictionary fields to constructor parameters when deserializing data. Reached for whenever you receive a flat dictionary (e.g., from JSON parsing) and need to instantiate a matching object.

@classmethod\ndef from_dict(cls, data):\n return cls(**data)

@property def getter_name(self): return self.attribute
CAT_6

The @property decorator converts a zero-argument method into a computed attribute, accessible without parentheses like a plain attribute. It solves the problem of breaking the public API when evolving a simple attribute into a computed or validated one. You reach for it when callers must access a derived or validated value using attribute syntax rather than an explicit method call.

@property def getter_name(self): return self.attribute

@retry(tries=3, delay=1) def risky_op(): pass
CAT_6

Automatically retries a function call a specified number of times with a fixed delay between attempts when it raises an exception. Addresses transient failures in network or I/O operations where a single attempt is insufficient. Reached for whenever calling external services or resources that may intermittently fail.

@retry(tries=max_attempts, delay=wait_seconds) def function_name(): body

@cache(maxsize=128) def fib(n): return n if n<2 else fib(n-1)fib(n-2)
CAT_6

The @lru_cache decorator from functools memoizes a pure function's return values in a bounded LRU cache, eliminating redundant recomputation for repeated calls with identical arguments. It addresses the exponential time blowup of naive recursive algorithms by trading memory for speed. You reach for it whenever a deterministic function is invoked repeatedly with overlapping inputs, most commonly in recursive divide-and-conquer or dynamic-programming solutions.

@lru_cache(maxsize=maxsize) def func(arg): return ...

@validate(min=0, max=100) def process_value(x): return x
CAT_6

Applies a range-validation decorator to a function, ensuring the argument falls within [min, max] before the function body executes. Addresses the pain point of unchecked numeric inputs propagating invalid data through a pipeline. Reached for whenever a function acts as a gateway for bounded numeric data and must reject out-of-range values early.

@validate(min=min_value, max=max_value) def function_name(parameter): return parameter

@authenticate(role='admin') def admin_only(): return 'secret'
CAT_6

Applies a parameterized decorator to a function to enforce role-based access control before the function body executes. Eliminates the need to manually check permissions inside each handler, which scatters authorization logic and invites omission bugs. Reached for whenever a route or operation must be restricted to users holding a specific role.

@authenticate(role=role) def function_name(): ...

@rate_limit(calls=5, period=10) def api_call(): pass
CAT_6

Applies a rate limiter to a function, allowing at most N calls within a given time period. This prevents excessive calls to APIs or resources and helps avoid HTTP 429 errors.

@rate_limit(calls=limit, period=seconds) def func(): pass

@timeout(seconds=3) def slow_task(): pass
CAT_6

Applies a timeout decorator that limits the decorated function's execution to the specified number of seconds, raising a timeout exception if exceeded.

@timeout(seconds=seconds) def function_name(): function_body

self.assertFalse
CAT_8

Asserts that an expression evaluates to False within a unittest.TestCase method. Solves the readability problem of writing self.assertTrue(not condition) or self.assertEqual(condition, False), making negative expectations explicit and intent-clear. Reached for when a test must verify that a function returns False, a feature flag is disabled, or an error condition is not met.

self.assertFalse(condition)

assert 'error' not in log_output
CAT_8

Asserts that the substring 'error' does not appear in the log output string, indicating that no error messages were logged during execution.

assert substring not in log_output

with pytest.raises(TypeError): parse_input
CAT_8

Asserts that a callable raises a specific exception type when invoked inside a pytest context manager, verifying that error-handling code paths are triggered correctly. Addresses the pain point of untested failure modes where functions silently accept invalid input or raise the wrong exception type. Reached for whenever a function's contract specifies that it must reject certain inputs with a particular exception.

with pytest.raises(ExceptionType): function_call(arguments)

assert math.isclose
CAT_8

Checks that two floating-point numbers are approximately equal within a given relative tolerance, using an assertion to raise an AssertionError if they are not.

assert math.isclose(actual, expected, rel_tol=tolerance)

assert 'key' in result_dict
CAT_8

Asserts that a specific key exists in a dictionary using Python's membership test operator. Catches missing keys early before they cause a KeyError deeper in the call stack. Reached for when a function's contract requires certain dictionary keys to be present and you want to fail fast with a clear error message.

assert key in dictionary

assert any
CAT_8

Returns True if any element in the iterable collection equals the target value; essentially a lazy membership test using any with a generator expression.

any(item == target for item in collection)

with pytest.raises(ValueError, match='invalid input'): parse_config
CAT_8

A pytest context manager that asserts a specific exception type is raised inside its block and optionally verifies the exception message matches a regex pattern. It addresses the pain point of testing error paths where simply confirming code runs without errors is insufficient. You reach for this when you need to verify that invalid inputs or edge cases raise the expected exceptions with meaningful messages.

with pytest.raises(exception_type, match=pattern): callable_under_test(*args, **kwargs)

assert sorted(actual_list) == sorted
CAT_8

This pattern asserts that two lists contain the same elements regardless of order by sorting both lists and comparing them for equality. It is commonly used in tests where the order of items is irrelevant or nondeterministic. Sorting provides a simple way to achieve multiset equality when elements are sortable.

assert sorted(actual_list) == sorted(expected_list)

assert pytest.approx(computed, rel=1e-7) == expected_value
CAT_8

Compares floating-point values using a relative tolerance to avoid false failures from tiny rounding errors. Addresses the pain point of exact equality checks failing on floats due to representation limits. Triggered when testing numerical computations or scientific code.

assert pytest.approx(computed, rel=tolerance) == expected

class MyTestCase(unittest.TestCase):
CAT_8

A class definition that inherits from unittest.TestCase to create a test case class for grouping unit test methods.

class test_case_name(unittest.TestCase):

def test_example(self):
CAT_8

Defines a test method that the test runner automatically discovers and executes based on the test_ name prefix. Solves the problem of distinguishing verification logic from helper methods within a test class. Reached for whenever a new scenario needs to be verified in an automated test suite.

def test_name(self):

def tearDown(self):
CAT_8

The tearDown method is a special method in unittest.TestCase that is invoked after each test method to clean up resources allocated during setUp or the test.

def tearDown(self): cleanup_statements

self.assertTrue
CAT_8

Asserts that the given expression evaluates to a truthy value in a unittest test method. Addresses the need to verify that a specific condition or invariant holds after exercising code under test. Reached for whenever a boolean or truthiness check is the most natural way to express a test expectation.

self.assertTrue(condition)

with self.assertRaises(KeyError):
CAT_8

Asserts that a block of code raises a specified exception, used in unit tests to verify error handling. It ensures that the tested code path correctly raises the expected exception, making test intent explicit and reducing boilerplate try/except code.

with self.assertRaises(exception_type):

@pytest.mark.parametrize('a,b,expected'
CAT_8

Decorates a test function so pytest runs it once per input dataset, passing each argument set as separate parameters. It eliminates the need to write repetitive near-identical test functions that differ only in input and expected output. You reach for it whenever a single test logic must be verified against multiple input-output pairs.

@pytest.mark.parametrize(argnames, argvalues) def test_function(arg1, arg2, expected): assert function_under_test(arg1, arg2) == expected

def test_sum(, , ): assert ==
CAT_8

A unit test that asserts the sum of two inputs equals an expected result.

def test_sum(<arg1>, <arg2>, <expected>): assert <arg1> + <arg2> == <expected>

for args in; test_func
CAT_8

Iterates over a sequence of argument tuples, unpacking each to call a function. Avoids the verbosity and error-proneness of manually indexing each argument position. Reached for when applying the same operation to multiple grouped parameter sets.

for args in arg_tuples: func(*args)

@pytest.mark.parametrize('input,expected'
CAT_8

Parametrizes a pytest test function with multiple sets of input arguments and expected results.

@pytest.mark.parametrize('param_names', [(arg1, expected1), (arg2, expected2), ...])

def test_function_name(value, expected): assert function_under_test(value) is expected
CAT_8

A parametrized test function that verifies a function's return value matches an expected result using identity comparison. Addresses the need to systematically validate function behavior against known inputs and outputs. Used when writing unit tests for functions that return singleton values like booleans or None.

def test_function_name(value, expected): assert function_under_test(value) is expected

@pytest.mark.parametrize('value,expected'
CAT_8

Decorates a test function to run it multiple times with different argument combinations, where each case is wrapped in pytest.param() with a custom id for clear identification in test reports. It solves the problem of undifferentiated parametrized test names that make it hard to pinpoint which specific input caused a failure. You reach for this when you need named, traceable test cases rather than opaque numeric indices.

@pytest.mark.parametrize(argnames, [pytest.param(argval1, argval2, id=test_id)])

@pytest.mark.parametrize('value,expected'; ids=
CAT_8

Decorates a test function to run it multiple times with different argument sets, treating each combination as a distinct test case. It addresses the pain point of duplicating test logic for different inputs and expected outputs. Reach for it when you need to verify a function's behavior across a matrix of inputs.

@pytest.mark.parametrize(argnames, argvalues, ids=test_ids)

pytest.param
CAT_8

Represents a parametrized test case that is expected to fail (xfail), used to verify that invalid input is properly rejected.

pytest.param(<arg1>, <arg2>, id='<identifier>', marks=pytest.mark.xfail)

@pytest.fixture
CAT_8

Declares a function as a pytest fixture that provides setup, teardown, and dependency injection for tests. It addresses the pain point of repetitive test initialization and cleanup code. You reach for it when multiple tests need the same baseline state or resources.

@pytest.fixture(...)

def sample_fixture(): return 42
CAT_8

Defines a minimal fixture function that returns a constant value, eliminating the need to hardcode the same literal across multiple test functions. Used when tests require a predictable, deterministic input that does not depend on external state or computation, and the value is simple enough that no setup or teardown logic is needed.

def fixture_name(): return literal_value

@pytest.fixture
CAT_8

A pytest fixture decorator that declares a fixture with module scope, meaning the fixture function is executed once per module and its result is shared across all test functions in that module.

@pytest.fixture(scope='module')

def test_example(sample_fixture): assert sample_fixture == 42
CAT_8

Asserts that the fixture sample_fixture equals the integer 42, used as a simple sanity check in a unit test.

def test_<name>(<fixture>): assert <fixture> == <expected_literal>

@pytest.fixture
CAT_8

A pytest fixture decorator that marks a fixture to be automatically used for all tests in its scope without requiring an explicit request.

@pytest.fixture(autouse=True)\ndef <fixture_name>():\n <setup>\n yield\n <teardown>

@pytest.fixture(params=; ) def param_fixture(request): return request.param
CAT_8

A pytest fixture that provides parameterized values (10, 20, 30) to test functions that request it via request.param.

@pytest.fixture(params=[<values>])\ndef <fixture_name>(request): return request.param

def test_using_fixture(db_conn): assert db_conn.is_connected()
CAT_8

A test that verifies the database connection fixture provides an active connection.

def test_<name>(fixture): assert fixture.method()

@pytest.fixture def fixture_name(tmp_path_factory): return tmp_path_factory.mktemp(prefix)
CAT_8

Defines a pytest fixture that creates a temporary directory with a custom prefix using the session-scoped tmp_path_factory. Solves the problem of needing isolated, named temporary directories in test suites without manual cleanup. Reached for when the built-in tmp_path fixture does not provide enough control over directory naming or scope.

@pytest.fixture def fixture_name(tmp_path_factory): return tmp_path_factory.mktemp(prefix)

@pytest.fixture def mocker_fixture(mocker): return mocker.patch('my_module.my_func', return_value=123)
CAT_8

Defines a pytest fixture that creates a mock object replacing a specified function with one that returns a fixed value. Addresses the pain point of tests depending on external or non-deterministic functions. Reached for when a test needs a controlled, predictable substitute for a real function.

@pytest.fixture def fixture_name(mocker): return mocker.patch('module_path.function_name', return_value=value)

def test_mocker_fixture(mocker_fixture): assert my_module.my_func() == 123
CAT_8

A pytest test function that receives the mocker fixture from the pytest-mock plugin, enabling patching and stubbing of dependencies within the test scope. It addresses the need to isolate units under test by replacing external calls with controlled substitutes. This pattern is reached for whenever a test requires mocking module-level objects, API calls, or other dependencies that make tests fragile or slow.

def test_name(mocker): mocker.patch(target, return_value=value) assert module.function() == expected

with patch('my_module.my_function') as mock_func:
CAT_8

Temporarily replaces a target function or object with a mock within a context block, restoring the original on exit. Addresses the pain of unrepeatable or side-effect-laden tests that depend on external systems or shared state. Reached for when a unit under test calls a dependency that must be controlled or verified in isolation.

with patch('module.function') as alias: