Skip to content

Decorator Functions

Rose Heart edited this page Feb 23, 2026 · 2 revisions

Imagine having a helpful assistant for your Python programs that quietly takes care of important but tedious tasks behind the scenes. This library acts like that assistant, making your functions smarter and more reliable without requiring you to rewrite your core logic. It gently wraps around your existing code to add three key superpowers: automatic logging of what your program does, precise timing of how long operations take, and graceful handling of unexpected problems. Think of it as giving your functions a safety net and a notebook all at once, so you can focus on solving problems rather than managing technical details.

One of the most useful features is how it handles your program's messages and results. Instead of losing important information that normally flashes by on your screen, this library can automatically save everything to a neatly organized log file. You decide where these logs go-either using a default file named after your script or choosing your own-and then forget about it. Every time your function runs, its printed messages get tucked away safely for you to review later, like having a patient secretary who takes perfect notes during every meeting.

Another handy tool measures exactly how long your functions take to complete their work. Whether your code is doing quick calculations or waiting for network responses, this feature quietly tracks the clock and reports back the duration in seconds. It works seamlessly for both regular functions and those handling multiple tasks at once, giving you clear insights into performance without cluttering your code with timing statements. This helps you spot slow spots in your program just by glancing at the output, almost like having a built-in stopwatch that never misses a beat.

When things go wrong-which they sometimes do in programming-this library steps in to prevent crashes and confusion. It catches errors that might otherwise stop your program dead in its tracks, then logs exactly where and why the problem happened while keeping everything running smoothly. You can even set up friendly fallback responses for tricky situations, like division by zero, so your program handles hiccups with quiet dignity instead of loud failures. Together, these features create a calm, professional environment where your code can thrive even when facing the unexpected.

What makes this library special is how effortlessly it fits into your workflow. You add just a few simple words to your function definitions, and suddenly you gain all these benefits without messy extra code. It's designed to feel natural and unobtrusive, like putting on a comfortable pair of glasses that suddenly make everything clearer. Whether you're building a small script or a complex application, this tool helps you work smarter by turning routine maintenance into something that happens automatically, leaving you free to concentrate on what really matters-creating great software.


class PrintRedirector:

Non-technical

This class quietly captures everything your program would normally display on the screen during specific operations and instead saves it neatly into a text file, allowing you to review the output later without interrupting your workflow or cluttering the console, while automatically handling file setup and cleanup so you never have to worry about leaving files open or misplacing your records.

Technical

  • file: A string specifying the destination filename for captured output; if omitted, defaults to the current script's name with .log appended, determining where printed messages will be permanently stored.

Returns

Returns None.


def function_stdout(func_or_file=None):

Non-technical

This decorator quietly captures everything your function prints out and saves it to a text file for you to review later, so you don't have to watch the screen while your program runs; it automatically uses a sensible file name based on your script or lets you choose a specific file if you prefer, making it easy to keep track of results without cluttering your console.

Technical

  • func_or_file: Optional parameter that can be a callable (function), a string, or None. When used without parentheses (e.g., @function_stdout), it represents the function being decorated and triggers logging to a default file named after your script. When used with parentheses containing a string (e.g., @function_stdout('log.txt')), the string specifies the custom log file path. When called with empty parentheses (e.g., @function_stdout()), None is used and the default log file applies.

Returns

Returns a function.


def stdout_helper(func, file):

Non-technical

This helper quietly captures any messages a program would normally show on the screen and saves them directly into a chosen file, allowing you to review the complete activity history later without cluttering your current view or disrupting your workflow.

Technical

  • func: Represents the task to be modified; must be a callable object; determines which task's messages will be redirected to the file.
  • file: Represents the destination for saved messages; must be a string containing a valid file path; specifies where the redirected output will be written.

Returns

Returns a function that, when called, executes the original function with its output redirected to the specified file.


def function_timer(func):

Non-technical

This tool quietly checks how long each part of your work takes to finish and then shares that timing information with you, making it simple to spot areas that might be moving too slowly without requiring any changes to how you originally wrote your tasks.

Technical

  • func: The task to be measured; must be a function (either synchronous or asynchronous); the decorator creates a timed version of this task that reports the duration when executed.

Returns

Returns a function that, when called, executes the original function and returns its result after printing the time taken for execution.


def function_trapper(failed_result=None):

Non-technical

This tool helps your programs handle unexpected problems smoothly by allowing you to set a safe outcome for when things go wrong, so instead of crashing, the program can continue running with a result you choose, making your software more dependable and user-friendly.

Technical

  • failed_result: This parameter sets the value to return when the decorated function encounters an error. It can be any data type such as a number, text, or a special marker, and if not specified, it defaults to nothing meaning the function will return nothing in case of failure.

Returns

Returns a function.


def TestDecorators(a,b):

Non-technical

This function safely calculates how many times one number fits into another, providing a precise decimal answer when the math works correctly and automatically returning zero when the calculation cannot be completed-such as when trying to divide by nothing-while quietly tracking both the outcome and how long the process took for future review without disrupting the user's experience.

Technical

  • a: The number being divided (dividend), expected as an integer or float; larger values produce proportionally larger results when the divisor remains constant and valid.
  • b: The number used for division (divisor), expected as an integer or float; non-zero values determine the scale of the result inversely, while zero triggers a safe return of zero instead of causing errors.

Returns

Returns a float representing the exact quotient when division succeeds, otherwise returns the integer 0 when division fails due to invalid inputs like zero.