Browse Chunks

Showing 5851-5900 of 7392 chunks

functools.update_wrapper(wrapper, func)
CAT_6

Copies attributes such as __module__, __name__, __doc__, and __annotations__ from a source function to a wrapper function. This preserves metadata that would otherwise be lost when decorating a function. Used when writing decorators that need the wrapped function to retain its original identity for introspection, documentation, and debugging.

functools.update_wrapper(wrapper, func)

@functools.wraps(original) def inner(*args, **kwargs): return original(*args, **kwargs)
CAT_6

The @functools.wraps decorator copies essential metadata such as __name__, __doc__, __module__, and __annotations__ from the original function to the wrapper function. Without it, a wrapper function would lose this metadata, making introspection, debugging, and documentation tools show the wrapper’s identity instead of the original’s. It is used whenever a decorator defines a wrapper function and needs the wrapped function to retain its original attributes for proper behavior in frameworks and debugging.

@functools.wraps(wrapped) def wrapper(*args, **kwargs): return wrapped(*args, **kwargs)

functools.update_wrapper(wrapper, func, assigned=('__module__', '__name__', '__qualname__', '__doc__', '__annotations__'))
CAT_6

Copies selected attributes (__module__, __name__, __qualname__, __doc__, __annotations__) from the original function to a wrapper function, preserving metadata for debugging and introspection.

@functools.wraps(func, assigned=('__module__', '__name__', '__doc__')) async def wrapper(*args, **kwargs): return await func(*args, **kwargs)
CAT_6

A decorator factory that creates an async wrapper preserving the original function's __module__, __name__, and __doc__ attributes via functools.wraps.

@functools.wraps(func, assigned=('__module__', '__name__', '__doc__')) async def wrapper(*args, **kwargs): return await func(*args, **kwargs)

functools.wraps(func)(lambda *args, **kwargs: func(*args, **kwargs))
CAT_6

functools.wraps copies essential attributes (__name__, __module__, __qualname__, __doc__, __annotations__) from the original function to the wrapper function. Without it, a decorator would hide the original function's identity, breaking introspection tools like help() and debugging. You reach for this pattern when you need to add behavior via a decorator while preserving the wrapped function's metadata.

functools.wraps(original_func)(lambda *args, **kwargs: original_func(*args, **kwargs))

@functools.wraps(method)\ndef wrapper(self, *args, **kwargs):\n return method(self, *args, **kwargs)
CAT_6

functools.update_wrapper(wrapper, func, assigned=('__module__', '__name__', '__qualname__'), updated=())
CAT_6

Copies attributes like __module__, __name__, and __qualname__ from a function to a wrapper function, preserving metadata for debugging and introspection.

@functools.wraps(func)\ndef wrapper(*args, **kwargs):\n wrapper.calls += 1\n return func(*args, **kwargs)
CAT_6

A decorator that counts how many times a wrapped function is called while preserving the original function's metadata via functools.wraps.

def decorator(func):\n @functools.wraps(func)\n def wrapper(*args, **kwargs):\n return func(*args, **kwargs)\n return wrapper
CAT_6

A minimal decorator that preserves the original function's metadata while transparently forwarding all arguments and return values.

@dec1 @dec2 def foo():
CAT_6

A Python function definition with two decorators applied.

@dec1 @dec2 def <function_name>([params]):

@staticmethod @classmethod def bar(cls):
CAT_6

@property @lru_cache def baz(self):
CAT_6

@trace @memoize def qux(x):
CAT_6

A Python function decorated with @trace and @memoize to enable call tracing and result caching.

@cache_result @timeout(seconds=30) def fetch_data(url):
CAT_6

Applies caching and a timeout to a function that fetches data from a URL.

@cache_result @timeout(seconds=30) def <function_name>(<params>):

@requires_auth @audit_log def delete_resource(resource_id):
CAT_6

Applies authentication and audit logging decorators to a delete resource function.

@requires_auth @audit_log def <function_name>(<params>):

@validate_input @sanitize_output def process_form(data):
CAT_6

A Python function that processes form data with input validation and output sanitization decorators.

@validate_input @sanitize_output def process_form(data):

@retry(max_attempts=3) @backoff(factor=2) def unstable_call():
CAT_6

This chunk applies a retry decorator with exponential backoff to a function call. It addresses transient failures in unreliable external services or networks. It is triggered when a function may fail intermittently and needs automatic retry attempts.

@retry(max_attempts=attempts) @backoff(factor=backoff_factor) def func():

@logger
CAT_6

A decorator that adds logging to a function or method.

@logger

@timer
CAT_6

The @timer decorator wraps a function to measure its execution time, typically printing or logging the duration. It addresses the pain point of manually adding timing code inside functions, which clutters logic and is error-prone. Developers reach for it when they need quick performance insights during development or optimization.

@timer

def logger(func): def wrapper(*args, **kwargs): print(f'Calling {func.__name__} with args={args}, kwargs={kwargs}') return func(*args, **kwargs) return wrapper
CAT_6

A higher-order function that wraps another function to log its call signature (function name, positional args, keyword args) before delegating to the original function.

def logger(func):\n def wrapper(*args, **kwargs):\n print(f'Calling {func.__name__} with args={args}, kwargs={kwargs}')\n return func(*args, **kwargs)\n return wrapper

def timer(func): def wrapper(*args, **kwargs): import time start = time.perf_counter() result = func(*args, **kwargs) elapsed = time.perf_counter() - start print(f'{func.__name__} executed in {elapsed:.4f} sec') return result return wrapper
CAT_6

A decorator that measures and prints the execution time of a function.

decorator

@functools.wraps(func)
CAT_6

logging.getLogger(__name__).info(f'{func.__name__} called with args={args}, kwargs={kwargs}')
CAT_6

Logs a function call with its name and arguments for debugging/tracing.

logging.getLogger(__name__).info(f'{func.__name__} called with args={args}, kwargs={kwargs}')

elapsed = time.perf_counter() - start; logging.getLogger(__name__).debug(f'{func.__name__} finished in {elapsed:.4f}s')
CAT_6

Measures elapsed time using time.perf_counter and logs a debug message with the function name and duration.

class Meta(type):
CAT_6

Defines a custom metaclass by subclassing type, allowing customization of class creation.

def __new__(cls, name, bases, dct):
CAT_6

The __new__ method is a static method that creates and returns a new class object. It receives the metaclass (cls), the class name, base classes, and namespace dictionary, and is responsible for object creation before __init__ is called.

def __new__(cls, name, bases, dct):

def __init__(cls, name, bases, dct):
CAT_6

The __init__ method of a metaclass, called after a class is created to initialize the class object.

def __init__(cls, name, bases, dct):

class MyClass(metaclass=Meta):
CAT_6

Defines a class named MyClass with a custom metaclass Meta.

class <ClassName>(metaclass=<MetaClass>):

super().__new__(cls, name, bases, dct)
CAT_6

Calls the parent metaclass's __new__ method to create a new class object, passing the metaclass, class name, base classes, and namespace dictionary.

super().__init__(cls, name, bases, dct)
CAT_6

Calls the parent metaclass’s __init__ method with the class object, name, bases, and attribute dictionary to complete class initialization. This avoids manually replicating the parent’s initialization logic and ensures proper setup of class attributes. It is triggered when defining a custom metaclass and needing to initialize the class after its creation.

super().__init__(cls, name, bases, dct)

@property
CAT_6

The @property decorator transforms a method into a getter for a read-only attribute, or with setter and deleter methods, into a managed attribute. It addresses the need for controlled attribute access (e.g., validation, lazy loading) without sacrificing the simplicity of attribute syntax. Developers reach for it when they want to encapsulate attribute access logic while providing a clean public interface.

@property

@classmethod
CAT_6

A decorator that transforms a method into a class method, receiving the class as its first argument (cls).

@classmethod

def my_decorator(func):\n def wrapper():\n print('before')\n result = func()\n print('after')\n return result\n return wrapper
CAT_6

A simple decorator that prints a message before and after calling the wrapped function.

def <decorator_name>(func):\n def wrapper(*args, **kwargs):\n <before>\n result = func(*args, **kwargs)\n <after>\n return result\n return wrapper

@lru_cache(maxsize=128)
CAT_6

@lru_cache wraps a function to cache its return values based on arguments, using a least-recently-used eviction policy when maxsize is exceeded. It avoids expensive recomputation of pure functions with repeated inputs. You reach for it when a deterministic function is called multiple times with the same arguments and you want to speed up execution.

@lru_cache(maxsize=max_size)

@retry(tries=3, delay=2)
CAT_6

The @retry decorator automatically re-executes a function when it raises an exception, allowing a configurable number of attempts and delay between retries. It addresses the pain point of transient failures in external calls, such as network glitches or service throttling, which often resolve on retry. Developers reach for this chunk when wrapping unreliable I/O operations, API clients, or any function that may fail intermittently but succeed on subsequent tries.

@retry(tries=attempts, delay=delay)

class CountCalls: def __init__(self, func): self.func = func self.count = 0 def __call__(self, *args, **kwargs): self.count += 1 print(f"Call {self.count} of {self.func.__name__}") return self.func(*args, **kwargs)
CAT_6

def debug(func): @functools.wraps(func) def wrapper(*args, **kwargs): args_repr = [repr(a) for a in args] kwargs_repr = [f"{k}={v!r}" for k, v in kwargs.items()] signature = ", ".join(args_repr + kwargs_repr) print(f"Calling {func.__name__}({signature})") result = func(*args, **kwargs) print(f"{func.__name__!r} returned {result!r}") return result return wrapper
CAT_6

A decorator that logs function calls and return values for debugging purposes.

def debug(func): @functools.wraps(func) def wrapper(*args, **kwargs): ... return wrapper

def singleton(cls): instances = {} def getinstance(*args, **kwargs): if cls not in instances: instances[cls] = cls(*args, **kwargs) return instances[cls] return getinstance
CAT_6

A decorator that ensures a class has only one instance, returning the same instance on every call.

class cached_property: def __init__(self, func): self.func = func self.attrname = None self.__doc__ = func.__doc__ def __set_name__(self, owner, name): self.attrname = name def __get__(self, instance, owner): if instance is None: return self if self.attrname is None: raise AttributeError value = self.func(instance) instance.__dict__[self.attrname] = value return value
CAT_6

A descriptor that caches the result of a method as an instance attribute after first access, returning the cached value on subsequent accesses.

__get__ descriptor that caches the result in instance.__dict__ after first access.

@decorator
CAT_6

A decorator is a function that modifies the behavior of another function or class without permanently changing its source code. It addresses the pain point of code duplication when applying the same cross-cutting concerns (like logging, timing, or access control) to multiple functions. It is triggered when developers need to add functionality to existing functions in a clean, reusable way.

@decorator_name def function_name(parameters): # function body pass

@functools.lru_cache(maxsize=128)
CAT_6

A decorator that caches the results of a function call based on its arguments, using a least-recently-used eviction policy when the cache exceeds maxsize entries.

@functools.lru_cache(maxsize=<N>)

@app.route('/api/data', methods=['GET'])
CAT_6

I'd like to
CAT_1

Expresses a polite want or desire, often used to make a request or state a preference in a non-demanding way.

I'd like to

and then
CAT_2

Used to link events in chronological sequence

and then

To begin with
CAT_3

Used to introduce the first point in a series or to start a discussion.

To begin with

I think
CAT_4

Used to express a personal belief or opinion, often softening the assertion.

I think

take action
CAT_5

to start doing something to deal with a problem or situation

take; action

wake up
CAT_6

stop sleeping; become alert

wake up

depend on someone/something/whether
CAT_7

to be influenced or determined by something else; to need support from

depend on

How's it going?
CAT_8

A casual, friendly greeting asking about someone's general state.

How's it going