Skip to content

Utils API 文档

概述

Utils 是 HeurAMS 的通用工具模块,提供各种辅助函数和工具类,用于支持其他模块的功能实现。

注意: 当前 utils 模块目录存在但为空,本文档基于常见的工具函数需求进行设计。

通用工具函数

1. 字符串处理

文本格式化

提供文本格式化和规范化功能。

核心函数:

  • normalize_text(text) - 规范化文本(去除多余空格、标准化标点)
  • truncate_text(text, max_length, suffix="...") - 截断文本
  • split_sentences(text) - 分割句子
  • remove_punctuation(text) - 移除标点符号

使用示例:

python
from heurams.utils.text import normalize_text, truncate_text

# 规范化文本
normalized = normalize_text("   Hello,   world!  ")
# 返回: "Hello, world!"

# 截断文本
truncated = truncate_text("这是一个很长的文本内容", 10)
# 返回: "这是一个很..."

字符串操作

提供字符串操作和转换功能。

核心函数:

  • camel_to_snake(text) - 驼峰命名转蛇形命名
  • snake_to_camel(text) - 蛇形命名转驼峰命名
  • slugify(text) - 生成 URL 友好的 slug
  • random_string(length) - 生成随机字符串

使用示例:

python
from heurams.utils.string import camel_to_snake, slugify

# 命名转换
snake_case = camel_to_snake("CamelCaseString")
# 返回: "camel_case_string"

# 生成 slug
slug = slugify("Hello World!")
# 返回: "hello-world"

2. 文件操作

路径处理

提供跨平台的路径处理功能。

核心函数:

  • ensure_dir(path) - 确保目录存在
  • safe_filename(filename) - 生成安全的文件名
  • get_file_extension(path) - 获取文件扩展名
  • join_paths(*paths) - 安全的路径拼接

使用示例:

python
from heurams.utils.file import ensure_dir, safe_filename

# 确保目录存在
ensure_dir("/path/to/directory")

# 生成安全文件名
safe_name = safe_filename("File/With\Invalid*Chars.txt")
# 返回: "File_With_Invalid_Chars.txt"

文件读写

提供安全的文件读写操作。

核心函数:

  • read_file_safe(path, encoding="utf-8") - 安全读取文件
  • write_file_safe(path, content, encoding="utf-8") - 安全写入文件
  • copy_file_safe(src, dst) - 安全复制文件
  • delete_file_safe(path) - 安全删除文件

使用示例:

python
from heurams.utils.file import read_file_safe, write_file_safe

# 安全读取文件
content = read_file_safe("config.toml")

# 安全写入文件
write_file_safe("output.txt", "Hello World")

3. 数据验证

类型检查

提供类型检查和验证功能。

核心函数:

  • is_valid_email(email) - 验证邮箱格式
  • is_valid_url(url) - 验证 URL 格式
  • is_numeric(value) - 检查是否为数字
  • is_list_of_type(items, item_type) - 检查列表元素类型

使用示例:

python
from heurams.utils.validation import is_valid_email, is_list_of_type

# 验证邮箱
if is_valid_email("user@example.com"):
    print("邮箱格式正确")

# 验证列表类型
numbers = [1, 2, 3]
if is_list_of_type(numbers, int):
    print("列表包含整数")

数据清理

提供数据清理和规范化功能。

核心函数:

  • clean_dict(data) - 清理字典(移除空值)
  • normalize_list(items) - 规范化列表(去重、排序)
  • sanitize_input(input_str) - 清理用户输入
  • escape_html(text) - HTML 转义

使用示例:

python
from heurams.utils.clean import clean_dict, sanitize_input

# 清理字典
data = {"name": "John", "age": None, "email": ""}
cleaned = clean_dict(data)
# 返回: {"name": "John"}

# 清理用户输入
safe_input = sanitize_input("<script>alert('xss')</script>")
# 返回: "&lt;script&gt;alert('xss')&lt;/script&gt;"

4. 日期时间工具

时间操作

提供日期时间操作功能。

核心函数:

  • format_duration(seconds) - 格式化时间间隔
  • parse_date(date_str) - 解析日期字符串
  • is_weekend(date) - 检查是否为周末
  • add_business_days(date, days) - 添加工作日

使用示例:

python
from heurams.utils.date import format_duration, add_business_days

# 格式化时间间隔
formatted = format_duration(3665)
# 返回: "1小时1分钟5秒"

# 添加工作日
from datetime import datetime
next_business_day = add_business_days(datetime.now(), 3)

5. 数学工具

数值计算

提供数学计算和统计功能。

核心函数:

  • clamp(value, min_val, max_val) - 限制数值范围
  • lerp(start, end, factor) - 线性插值
  • mean(values) - 计算平均值
  • standard_deviation(values) - 计算标准差

使用示例:

python
from heurams.utils.math import clamp, mean

# 限制数值范围
clamped = clamp(150, 0, 100)
# 返回: 100

# 计算平均值
average = mean([1, 2, 3, 4, 5])
# 返回: 3.0

6. 集合操作

集合工具

提供集合操作和数据处理功能。

核心函数:

  • flatten_list(nested_list) - 展平嵌套列表
  • chunk_list(items, chunk_size) - 分块列表
  • unique(items) - 去重(保持顺序)
  • group_by(items, key_func) - 按键分组

使用示例:

python
from heurams.utils.collections import flatten_list, chunk_list

# 展平嵌套列表
flattened = flatten_list([[1, 2], [3, [4, 5]]])
# 返回: [1, 2, 3, 4, 5]

# 分块列表
chunks = chunk_list([1, 2, 3, 4, 5], 2)
# 返回: [[1, 2], [3, 4], [5]]

装饰器工具

性能监控

提供函数性能监控装饰器。

核心装饰器:

  • @timer - 测量函数执行时间
  • @cache_result(ttl=3600) - 缓存函数结果
  • @retry(max_attempts=3) - 自动重试
  • @rate_limit(requests_per_minute=60) - 速率限制

使用示例:

python
from heurams.utils.decorators import timer, cache_result

@timer
def expensive_operation():
    # 耗时操作
    pass

@cache_result(ttl=300)  # 缓存5分钟
def get_expensive_data():
    # 获取昂贵数据
    return data

输入验证

提供函数参数验证装饰器。

核心装饰器:

  • @validate_args - 验证函数参数
  • @type_check - 类型检查
  • @non_null - 非空检查

使用示例:

python
from heurams.utils.decorators import validate_args, type_check

@validate_args
def create_user(name: str, age: int):
    # 参数自动验证
    pass

@type_check
def process_data(data: list, count: int) -> bool:
    # 类型自动检查
    return True

配置工具

环境变量

提供环境变量管理功能。

核心函数:

  • get_env(key, default=None) - 获取环境变量
  • set_env(key, value) - 设置环境变量
  • load_env_file(path) - 加载 .env 文件
  • is_production() - 检查是否为生产环境

使用示例:

python
from heurams.utils.env import get_env, load_env_file

# 加载环境文件
load_env_file(".env")

# 获取环境变量
debug_mode = get_env("DEBUG", False)
api_key = get_env("API_KEY")

配置解析

提供配置解析和合并功能。

核心函数:

  • merge_configs(*configs) - 合并多个配置
  • deep_update(target, source) - 深度更新字典
  • config_from_dict(data) - 从字典创建配置对象

使用示例:

python
from heurams.utils.config import merge_configs, deep_update

# 合并配置
base_config = {"debug": False, "port": 8000}
user_config = {"debug": True}
merged = merge_configs(base_config, user_config)
# 返回: {"debug": True, "port": 8000}

# 深度更新
target = {"a": 1, "b": {"c": 2}}
source = {"b": {"d": 3}}
updated = deep_update(target, source)
# 返回: {"a": 1, "b": {"c": 2, "d": 3}}

错误处理工具

异常处理

提供统一的异常处理机制。

核心函数:

  • safe_call(func, *args, **kwargs) - 安全调用函数
  • ignore_errors(func) - 忽略错误的装饰器
  • with_retry(func, max_attempts=3) - 带重试的上下文管理器

使用示例:

python
from heurams.utils.errors import safe_call, with_retry

# 安全调用
result = safe_call(risky_function, arg1, arg2)

# 带重试执行
with with_retry(max_attempts=5):
    unreliable_operation()

日志工具

提供简化的日志记录功能。

核心函数:

  • log_info(message, **extra) - 记录信息日志
  • log_warning(message, **extra) - 记录警告日志
  • log_error(message, exc_info=True, **extra) - 记录错误日志
  • setup_logging(level="INFO") - 设置日志配置

使用示例:

python
from heurams.utils.logging import log_info, log_error

# 记录日志
log_info("操作完成", user_id=123, operation="update")

try:
    risky_operation()
except Exception as e:
    log_error("操作失败", exc_info=True, user_id=123)

测试工具

测试辅助

提供测试相关的辅助函数。

核心函数:

  • create_mock_data(count) - 创建模拟数据
  • assert_dict_contains(subset, superset) - 断言字典包含
  • approx_equal(a, b, tolerance=1e-6) - 近似相等断言

使用示例:

python
from heurams.utils.testing import create_mock_data, assert_dict_contains

# 创建模拟数据
mock_users = create_mock_data(10)

# 断言字典包含
assert_dict_contains({"name": "John"}, user_data)

使用示例

综合使用

python
from heurams.utils.text import normalize_text, truncate_text
from heurams.utils.file import ensure_dir, write_file_safe
from heurams.utils.decorators import timer, cache_result

@timer
@cache_result(ttl=300)
def process_content(content):
    """处理内容并保存"""
    # 规范化文本
    normalized = normalize_text(content)

    # 截断预览
    preview = truncate_text(normalized, 100)

    # 确保目录存在
    ensure_dir("output")

    # 保存文件
    write_file_safe("output/processed.txt", normalized)

    return preview

# 使用工具函数
result = process_content("   这是一个测试内容,包含很多空格和  格式问题。   ")
print(result)  # 输出: "这是一个测试内容,包含很多空格和格式问题..."

错误处理示例

python
from heurams.utils.errors import safe_call
from heurams.utils.logging import log_error

# 安全执行可能失败的操作
def safe_data_processing():
    result = safe_call(unreliable_external_api)
    if result is None:
        log_error("外部API调用失败", api_name="external_api")
        return fallback_data
    return result

扩展接口

自定义工具

开发者可以创建自定义工具函数:

python
# 自定义文本处理工具
from heurams.utils.base import BaseTool

class CustomTextTool(BaseTool):
    def process(self, text):
        # 自定义处理逻辑
        return self.custom_processing(text)

# 注册自定义工具
ToolRegistry.register("custom_text", CustomTextTool)

工具组合

组合多个工具实现复杂功能:

python
from heurams.utils.compose import compose

# 组合工具函数
processing_pipeline = compose(
    normalize_text,
    lambda x: truncate_text(x, 200),
    safe_filename
)

# 应用处理管道
result = processing_pipeline(input_text)

兼容性说明

  • Python 版本: 需要 Python 3.8 或更高版本
  • 平台支持: 完全跨平台支持
  • 依赖项: 仅使用标准库,无外部依赖
  • 性能: 轻量级设计,低内存占用