Skip to main content

Python utility library with Result pattern for consistent error handling, file operations, parallel execution, and logging.

Project description

tbot223-core

PyPI Python License

Table of Contents

A zero-dependency Python toolkit for file operations, logging, exception tracking, and parallel execution, built around a Result pattern for predictable error handling.

한국어 (Korean)

Why tbot223-core?

Every public function returns a Result object instead of raising exceptions. This gives you a consistent, predictable shape for every operation — success or failure. No more wrapping every call in try/except; just check result.success or call .unwrap().

The core Result type was designed independently; the convenience methods unwrap(), expect(), and unwrap_or() were later inspired by Rust's Result<T, E>.

This package is a good fit if you:

  • Prefer explicit success/failure flows over catching exceptions everywhere
  • Want a ready-to-use toolkit for tools, scripts, and internal utilities
  • Prefer a consistent return shape over unexpected runtime tracebacks

This library follows an explicit success/failure pattern rather than Python's traditional exception-driven style.

Features

  • Consistent Result Objects — All functions return a standardized Result NamedTuple with success, error, context, and data fields
  • Robust File Management — Atomic writes (temp file + rename), JSON I/O, file locking for large files, directory operations
  • Advanced Logging System — Named loggers with automatic timestamped file organization, configurable levels, and a single-step SimpleSetting helper
  • Exception Tracking — Source location extraction, full traceback capture, system info caching, sensitive data masking
  • Parallel ExecutionThreadPoolExecutor and ProcessPoolExecutor wrappers with support for timeouts, chunking, and worker limits
  • Localization Support — JSON-based localization with internal caching and automatic reloads
  • Shared Memory IPC — Process-safe global variables with JSON/pickle serialization, LRU-cached handles, and ownership tracking

Installation

pip install tbot223-core

Requires Python 3.10 - 3.14. Zero external dependencies.

Quick Start

1. File operations with Result pattern

from tbot223_core import FileManager

fm = FileManager()

# Every operation returns a Result — no exceptions to catch
result = fm.write_json("config.json", {"key": "value"})

if result.success:
    print("Saved successfully")
else:
    print(f"Failed: {result.error}")

# unwrap() — returns data on success, raises ResultUnwrapException on failure
data = fm.read_json("config.json").unwrap()

# expect() — like unwrap(), but with a custom error message
data = fm.read_json("config.json").expect("Config file is required")

# unwrap_or() — returns data on success, or the default value on failure
data = fm.read_json("missing.json").unwrap_or({"default": True})

2. Auto-wrap any function with ResultWrapper

from tbot223_core import ResultWrapper

@ResultWrapper()
def divide(a, b):
    return a / b

result = divide(10, 2)
print(result.success)  # True
print(result.data)     # 5.0

result = divide(10, 0)
print(result.success)  # False
print(result.error)    # "ZeroDivisionError :division by zero"

3. Structured logging

from tbot223_core.LogSys import SimpleSetting

setting = SimpleSetting(
    base_dir=".",
    second_log_dir="my_app",
    logger_name="AppLogger",
)
logger_manager, log, logger = setting.get_instance()

log.log_message("INFO", "Application started")
log.log_message("ERROR", "Something went wrong")
# Log file: ./my_app/{timestamp}_log/AppLogger.log

4. Parallel execution

from tbot223_core import AppCore
import time

app = AppCore()

def slow_task(n):
    time.sleep(0.1)
    return n * 2

tasks = [(slow_task, {"n": i}) for i in range(10)]
result = app.thread_pool_executor(tasks, workers=4, timeout=5.0)
print([task_result.data for task_result in result.data])  # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

Imports

All core classes are available directly from tbot223_core:

from tbot223_core import (
    AppCore,                    # Parallel execution, CLI input, localization
    ResultWrapper,              # Decorator: wraps returns in Result
    FileManager,                # File I/O, JSON, atomic writes
    LoggerManager, Log,         # Structured logging
    ExceptionTracker,           # Exception info extraction
    ExceptionTrackerDecorator,  # Decorator: auto exception-to-Result
    Utils,                      # Hashing, path conversion, data manipulation
    GlobalVars,                 # Thread-safe global variables + shared memory
    DecoratorUtils,             # Runtime measurement
    Result,                     # The Result NamedTuple itself
)

# For Result-related exceptions:
from tbot223_core.Result import ResultUnwrapException

# For SimpleSetting (not re-exported at top level):
from tbot223_core.LogSys import SimpleSetting

Core Modules

Module Purpose Key Methods
AppCore Parallel execution, console, CLI input, localization thread_pool_executor(), process_pool_executor(), safe_CLI_input(), get_text_by_lang()
ResultWrapper Decorator: wraps any function's return in a Result @ResultWrapper()
FileManager Atomic writes, file/JSON I/O, directory operations atomic_write(), read_file(), write_json(), read_json(), exists()
LogSys Structured logging with auto file management make_logger(), get_logger(), log_message(), SimpleSetting
ExceptionTracker Exception location/info tracking, error code mapping get_exception_info(), get_exception_return(), get_error_code()
Utils Hashing, path conversion, PBKDF2, data manipulation hashing(), pbkdf2_hmac(), find_keys_by_value(), insert_at_intervals()
GlobalVars Thread-safe global variables with shared memory IPC set(), get(), shm_gen(), shm_sync(), shm_update(), shm_close()
DecoratorUtils Runtime measurement @DecoratorUtils.count_runtime()

See API Reference for full method signatures, parameters, and return values.

The Result Pattern

All public functions return a Result NamedTuple:

Result(
    success: Optional[bool],  # True = success, False = failure, None = cancelled
    error: Optional[str],     # Error message (None on success)
    context: Optional[str],   # Additional context (None on success)
    data: Any,                # Returned data, or failure details
)

On success, data contains the returned value. On failure, it may contain None, method-specific detail data, or a structured error_info dictionary produced by ExceptionTracker.

Methods

Method Behavior on success Behavior on failure
unwrap() Returns data Raises ResultUnwrapException
expect(msg) Returns data Raises ResultUnwrapException with custom msg
unwrap_or(default) Returns data Returns default

When unwrap() or expect() raises on a failed result, the exception keeps the original Result.data payload in ResultUnwrapException.data.

Examples

The examples/ directory contains 40+ runnable scripts organized by module. Each script is self-contained and prints TEST COMPLETE on success.

Module Examples
Result Basic usage, unwrap(), expect(), unwrap_or()
AppCore Thread/process pool executors, CLI input, multi-language, ResultWrapper
FileManager Atomic write, JSON I/O, file listing, directory operations
LogSys Logger creation, log messages, SimpleSetting single-step setup
ExceptionTracker Exception info, location tracking, error codes, decorator
Utils Hashing, PBKDF2, path conversion, interval insertion, dict search
GlobalVars Basic CRUD, attribute/call syntax, thread locking, shared memory IPC
DecoratorUtils Runtime measurement

See Examples.md for a full listing with descriptions.

Documentation

License

Apache License 2.0

Links

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

tbot223_core-4.0.0.tar.gz (39.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

tbot223_core-4.0.0-py3-none-any.whl (40.9 kB view details)

Uploaded Python 3

File details

Details for the file tbot223_core-4.0.0.tar.gz.

File metadata

  • Download URL: tbot223_core-4.0.0.tar.gz
  • Upload date:
  • Size: 39.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for tbot223_core-4.0.0.tar.gz
Algorithm Hash digest
SHA256 8dd352e96e726aef49343c3a91ca68b349f0c8377077ce4ffa252f1ee9cd1a94
MD5 6c392bfabbdc3eb94ccc357303c62f72
BLAKE2b-256 4a041165ea73d9a7473ab8352c1ab55d9fa02eab6d366153d593f0b011cd11fe

See more details on using hashes here.

Provenance

The following attestation bundles were made for tbot223_core-4.0.0.tar.gz:

Publisher: python-publish.yml on Tbot223/tbot223-core

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file tbot223_core-4.0.0-py3-none-any.whl.

File metadata

  • Download URL: tbot223_core-4.0.0-py3-none-any.whl
  • Upload date:
  • Size: 40.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for tbot223_core-4.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 a7b9bcf9878b3ed4429eda977b7c8ac508938d1b5278177061f247970651ed90
MD5 bccdddf2290affb6ecfd2c9aa2d4a365
BLAKE2b-256 64f85f6d2a2e4173263378e71f029acab3bc8478dfea4e3ad70940d08e870086

See more details on using hashes here.

Provenance

The following attestation bundles were made for tbot223_core-4.0.0-py3-none-any.whl:

Publisher: python-publish.yml on Tbot223/tbot223-core

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page