详解Python中通用工具类与异常处理

2024-12-29 03:50

本文主要是介绍详解Python中通用工具类与异常处理,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

《详解Python中通用工具类与异常处理》在Python开发中,编写可重用的工具类和通用的异常处理机制是提高代码质量和开发效率的关键,本文将介绍如何将特定的异常类改写为更通用的ValidationEx...

python开发中,编写可重用的工具类和通用的异常处理机制是提高代码质量和开发效率的关键www.chinasem.cn。本文将介绍如何将特定的异常类GlueValidaionException改写为更通用的ValidationException,并创建一个通用的工具类Utils,包含常用的文件操作和数据处理方法。最后,我们将通过代码示例展示如何使用这些工具。

1. 通用异常类:ValidationException

首先,我们将GlueValidaionException改写为更通用的ValidationException,使其适用于各种验证场景。

class ValidationException(Exception):
    """
    通用验证异常类,适用于各种验证场景。
    """
    def __init__(self, err_message, excep_obj):
        message = ("[Invalid input detected]\n"
                   f"Exception: {err_message}\n"
                   f"Exception logs: {excep_obj}")
        super().__init__(message)

2. 通用工具类:Utils

接下来,我们创建一个通用的工具类Utils,包含常用的文件操作和数据处理方法。

import json
from os.path import join
from typing import Dict, List
import yaml

class Utils:
    @staticmethod
    def yaml_to_dict(file_path: str) -> Dict:
        """
        将YAML文件转换为字典。
        
        :param file_path: YAML文件路径
        :return: 解析后的字典
        """
        with open(file_path) as yaml_file:
            yaml_string = yaml_file.read()
            try:
                parsed_dict = yaml.safe_load(yaml_string)
            except yaml.scanner.ScannerError as e:
                raise ValidationException(f"YAML文件语法错误: {file_path}", e)
        return parsed_dict

    @staticmethod
    def yaml_to_class(yaml_file_paphpth: str, cls: type, default_yaml_file_path: str = None):
        """
        将YAML文件转换为类对象。
        
        :param yaml_file_path: YAML文件路径
        :param cls: 目标类
        :param default_yaml_file_path: 默认YAML文件路径
        :return: 类对象
        """
        if not yaml_file_path:
            yaml_file_path = default_yaml_file_path
        custom_args = Utils.yaml_to_dict(yaml_file_path)

        if default_yaml_file_path:
            default_args = Utils.yaml_to_dict(default_yaml_file_path)
            missing_args = set(default_args) - set(custom_args)
            for key in list(missing_args):
                custom_args[key] = default_args[key]

        try:
            yaml_as_class = cls(**custom_args)
        except TypeError as e:
            raise ValidationException(f"YAML文件转换为类失败: {yaml_file_path}", e)

        return yaml_as_class

    @staticmethod
    def read_jsonl(file_path: str) -> List:
        """
        读取JSONL文件并返回所有JSON对象列表。
        
        :param file_path: JSONL文件路径
        :return: JSON对象列表
        """
        jsonl_list = []
        with open(file_path, "r") as fileobj:
            while True:
                single_row =php fileobj.readline()
                if not single_row:
                    break
                json_object = json.loads(single_row.strip())
                jsonl_list.append(json_object)
        return jsonl_list

    @staticmethod
    def read_jsonl_row(file_path: str):
        """
        逐行读取JSONL文件并返回JSON对象。
        
        :param file_path: JSONL文件路径
        :return: JSON对象生成器
        """
        with open(file_path, "r") as fileobj:
            while True:
                try:
                    single_row = fileobj.readline()
                    if not single_row:
                        break
                    json_object = json.loads(single_row.strip())
                    yield json_object
                except json.JSONDecodeError as e:
                    print(f"JSONL文件读取错误: {file_path}. 错误: {e}")
                    continue

    @staticmethod
    def append_as_jsonl(file_path: str, args_to_log: Dict):
        """
        将字典追加到JSONL文件中。
        
        :param file_path: JSONL文件路径
        :param args_to_log: 要追加的字典
        """
        json_str = json.dumps(args_to_log, default=str)
        with open(file_path, "a") as fileobj:
            fileobj.write(json_str + "\n")

    @staticmethod
    def save_jsonlist(file_path: str, json_list: List, mode: str = "a"):
        """
        将JSON对象列表保存到JSONL文件中。
        
        :param file_path: JSONL文件路径
        :param json_list: JSON对象列表
        :param mode: 文件写入模式
        """
        with open(file_path, mode) as file_obj:
            for json_obj in json_list:
                json_str = json.dumps(json_obj, default=str)
                file_obj.write(json_str + "\n")

    @staticmethod
    def str_list_to_dir_path(str_list: List[str]) -> str:
        """
        将字符串列表拼接为目录路径。
        
        :param str_list: 字符串列表
        :return: 拼接后的目录路径
        """
        if not str_list:
            return ""
        path = ""
        for dir_name in str_list:
            path = join(path, dir_name)
        return path

3. 示例文件内容

以下是示例文件的内容,包括default_config.yaml、config.yaml和data.jsonl。

default_config.yaml

name: "default_name"
value: 100
description: "This is a default configuration."

config.yaml

name: "custom_name"
value: 200

data.jsonl

{"id": 1, "name": "Alice", "age": 25}
{"id": 2, "name": "Bob", "age": 30}
{"id": 3, "name": "Charlie", "age": 35}

4. 代码示例

以下是如何使用Utils工具类的示例:

# 示例类
class Config:
    def __init__(self, name, value, description=None):
        self.name = name
        self.value = value
        self.description = description

# 示例1: 将YAML文件转换为字典
yaml_dict = Utils.yaml_to_dict("config.yaml")
print("YAML文件转换为字典:", yaml_dict)

# 示例2: 将YAML文件转换为类对象
config_obj = Utils.yaml_to_class("config.yaml", Config, "default_config.yaml")
print("YAML文件转换为类对象:", config_obj.phpname, config_obj.value, config_obj.description)

# 示例3: 读取JSONL文件
jsonl_list = Utils.read_jsonl("data.jsonl")
print("读取JSONL文件:", jsonl_list)

# 示例4: 逐行读取JSONL文件
print("逐行读取JSONL文件:")
for json_obj in Utils.read_jsonl_row("data.jsonl"):
    print(json_obj)

# 示例5: 将字典追加到JSONL文件
Utils.append_as_jsonl("data.jsonl", {"id": 4, "name": "David", "age": 40})
print("追加数据到JSONL文件完成")

# 示例6: 将JSON对象列表保存到JSONL文件
Utils.save_jsonlist("data.jsonl", [{"id": 5, "name": "Eve", "age": 45}])
print("保存JSON列表到JSONL文件完成")

# 示例7: 将字符串列表拼接为目录路径
path = Utils.str_list_to_dir_path(["dir1", "dir2", "dir3"])
print("拼接目录路径:", path)

5. 运行结果

运行上述代码后,输出结果如下:

YAML文件转换为字典: {'name': 'custom_name', 'value': 200}
YAML文件转换为类对象: custom_name 200 This is a default configuration.
读取JSONL文件: [{'id': 1, 'name': 'Alice', 'age': 25}, {'id': 2, 'name': 'Bob', 'age': 30}, {'id': 3, 'name': 'Charlie', 'age': 35}]
逐行读取JSONL文件:
{'id': 1, 'name': 'Alice', 'age': 25}
{'id': 2, 'name': 'Bob', 'age': 30}
{'id': 3, 'name': 'Charlie', 'age': 35}
追加数据到JSONL文件完成
保存JSON列表到JSONL文件完成
拼接目录路径: dir1/dir2/dir3

6. 完整代码

import json
from os.path import join
from typing import Dict, List

import yaml
from yaml.scanner import ScannerError


class ValidationException(Exception):
    """
    通用验证异常类,适用于各种验证场景。
    """

    def __init__(self, err_message, excep_obj):
        message = ("[Invalid input detected]\n"
                   f"Exception: {err_message}\n"
                   f"Exception logs: {excep_obj}")
        super().__init__(message)


class Utils:
    @staticmethod
    def yaml_to_dict(file_path: str) -> Dict:
        """
        将YAML文件转换为字典。

        :param file_path: YAML文件路径
        :return: 解析后的字典
        """
        with open(file_path) as yaml_file:
            yaml_string = yaml_file.read()
            try:
                parsed_dict = yaml.safe_load(yaml_string)
            except ScannerError as e:
                raise ValidationException(f"YAML文件语法错误: {file_path}", e)
        return parsed_dict

    @staticmethod
    def yaml_to_class(yaml_file_path: str, cls: type, default_yaml_file_path: str = None):
        """
        将YAML文件转换为类对象。

        :param yaml_file_path: YAML文件路径
        :param cls: 目标类
        :param default_yaml_file_path: 默认YAML文件路径
        :returPkmfuFZYn: 类对象
        """
        if not yaml_file_path:
            yaml_file_path = default_yaml_file_path
        custom_args = Utils.yaml_to_dict(yaml_file_path)

        if default_yaml_file_path:
            default_args = Utils.yaml_to_dict(default_yaml_file_path)
            missing_args = set(default_args) - set(custom_args)
            for key in list(missing_args):
                custom_args[key] = default_args[key]

        try:
            yaml_as_class = cls(**custom_args)
        except TypeError as e:
            raise ValidationException(f"YAML文件转换为类失败: {yaml_file_path}", e)

        return yaml_as_class

    @staticmethod
    def read_jsonl(file_path: str) -> List:
        """
        读取JSONL文件并返回所有JSON对象列表。

        :param file_path: JSONL文件路径
        :return: JSON对象列表
        """
        jsonl_list = []
        with open(file_path, "r") as file_obj:
            while True:
                single_row = file_obj.readline()
                if not single_row:
                    break
                json_obj = json.loads(single_row.strip())
                jsonl_list.append(json_obj)
        return jsonl_list

    @staticmethod
    def read_jsonl_row(file_path: str):
        """
        逐行读取JSONL文件并返回JSON对象。

        :param file_path: JSONL文件路径
        :return: JSON对象生成器
        """
        with open(file_path, "r") as file_object:
            while True:
                try:
                    single_row = file_object.readline()
                    if not single_row:
                        break
                    json_obj = json.loads(single_row.strip())
                    yield json_obj
                except json.JSONDecodeError as e:
                    print(f"JSONL文件读取错误: {file_path}. 错误: {e}")
                    continue

    @staticmethod
    def append_as_jsonl(file_path: str, args_to_log: Dict):
        """
        将字典追加到JSONL文件中。

        :param file_path: JSONL文件路径
        :param args_to_log: 要追加的字典
        """
        json_str = json.dumps(args_to_log, default=str)
        with open(file_path, "a") as file_object:
            file_object.write(json_str + "\n")

    @staticmethod
    def save_jsonlist(file_path: str, json_list: List, mode: str = "a"):
        """
        将JSON对象列表保存到JSONL文件中。

        :param file_path: JSONL文件路径
        :param json_list: JSON对象列表
        :param mode: 文件写入模式
        """
        with open(file_path, mode) as file_obj:
            for json_obj in json_list:
                json_str = json.dumps(json_obj, default=str)
                file_obj.write(json_str + "\n")

    @staticmethod
    def str_list_to_dir_path(str_list: List[str]) -> str:
        """
        将字符串列表拼接为目录路径。

        :param str_list: 字符串列表
        :return: 拼接后的目录路径
        """
        if not str_list:
            return ""
        dir_path = ""
        for dir_name in str_list:
            dir_path = join(dir_path, dir_name)
        return dir_path


# 示例类
class Config:
    def __init__(self, name, value, description=None):
        self.name = name
        self.value = value
        self.description = description


# 示例1: 将YAML文件转换为字典
yaml_dict = Utils.yaml_to_dict("config.yaml")
print("YAML文件转换为字典:", yaml_dict)

# 示例2: 将YAML文件转换为类对象
config_obj = Utils.yaml_to_class("config.yaml", Config, "default_config.yaml")
print("YAML文件转换为类对象:", config_obj.name, config_obj.value, config_obj.description)

# 示例3: 读取JSONL文件
jsonl_list = Utils.read_jsonl("data.jsonl")
print("读取JSONL文件:", jsonl_list)

# 示例4: 逐行读取JSONL文件
print("逐行读取JSONL文件:")
for json_obj in Utils.read_jsonl_row("data.jsonl"):
    print(json_obj)

# 示例5: 将字典追加到JSONL文件
Utils.append_as_jsonl("data.jsonl", {"id": 4, "name": "David", "age": 40})
print("追加数据到JSONL文件完成")

# 示例6: 将JSON对象列表保存到JSONL文件
Utils.save_jsonlist("data.jsonl", [{"id": 5, "name": "Eve", "age": 45}])
print("保存JSON列表到JSONL文件完成")

# 示例7: 将字符串列表拼接为目录路径
path = Utils.str_list_to_dir_path(["dir1", "dir2", "dir3"])
print("拼接目录路径:", path)

7. 总结

通过将特定的异常类改写为通用的ValidationException,并创建一个包含常用方法的Utils工具类,我们可以大大提高代码的复用性和可维护性。本文提供的代码示例展示了如何使用这些工具类进行文件操作和数据处理,适合初级Python程序员学习和参考。

到此这篇关于详解Python中通用工具类与异常处理的文章就介绍到这了,更多相关Python通用工具类与异常处理内容请搜索China编程(www.chinasem.cn)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程China编程(www.chinasem.cn)!

这篇关于详解Python中通用工具类与异常处理的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1152830

相关文章

Python实现AVIF图片与其他图片格式间的批量转换

《Python实现AVIF图片与其他图片格式间的批量转换》这篇文章主要为大家详细介绍了如何使用Pillow库实现AVIF与其他格式的相互转换,即将AVIF转换为常见的格式,比如JPG或PNG,需要的小... 目录环境配置1.将单个 AVIF 图片转换为 JPG 和 PNG2.批量转换目录下所有 AVIF 图

Python通过模块化开发优化代码的技巧分享

《Python通过模块化开发优化代码的技巧分享》模块化开发就是把代码拆成一个个“零件”,该封装封装,该拆分拆分,下面小编就来和大家简单聊聊python如何用模块化开发进行代码优化吧... 目录什么是模块化开发如何拆分代码改进版:拆分成模块让模块更强大:使用 __init__.py你一定会遇到的问题模www.

Java Predicate接口定义详解

《JavaPredicate接口定义详解》Predicate是Java中的一个函数式接口,它代表一个判断逻辑,接收一个输入参数,返回一个布尔值,:本文主要介绍JavaPredicate接口的定义... 目录Java Predicate接口Java lamda表达式 Predicate<T>、BiFuncti

详解如何通过Python批量转换图片为PDF

《详解如何通过Python批量转换图片为PDF》:本文主要介绍如何基于Python+Tkinter开发的图片批量转PDF工具,可以支持批量添加图片,拖拽等操作,感兴趣的小伙伴可以参考一下... 目录1. 概述2. 功能亮点2.1 主要功能2.2 界面设计3. 使用指南3.1 运行环境3.2 使用步骤4. 核

Python 安装和配置flask, flask_cors的图文教程

《Python安装和配置flask,flask_cors的图文教程》:本文主要介绍Python安装和配置flask,flask_cors的图文教程,本文通过图文并茂的形式给大家介绍的非常详细,... 目录一.python安装:二,配置环境变量,三:检查Python安装和环境变量,四:安装flask和flas

使用Python自建轻量级的HTTP调试工具

《使用Python自建轻量级的HTTP调试工具》这篇文章主要为大家详细介绍了如何使用Python自建一个轻量级的HTTP调试工具,文中的示例代码讲解详细,感兴趣的小伙伴可以参考一下... 目录一、为什么需要自建工具二、核心功能设计三、技术选型四、分步实现五、进阶优化技巧六、使用示例七、性能对比八、扩展方向建

一文详解JavaScript中的fetch方法

《一文详解JavaScript中的fetch方法》fetch函数是一个用于在JavaScript中执行HTTP请求的现代API,它提供了一种更简洁、更强大的方式来处理网络请求,:本文主要介绍Jav... 目录前言什么是 fetch 方法基本语法简单的 GET 请求示例代码解释发送 POST 请求示例代码解释

基于Python打造一个可视化FTP服务器

《基于Python打造一个可视化FTP服务器》在日常办公和团队协作中,文件共享是一个不可或缺的需求,所以本文将使用Python+Tkinter+pyftpdlib开发一款可视化FTP服务器,有需要的小... 目录1. 概述2. 功能介绍3. 如何使用4. 代码解析5. 运行效果6.相关源码7. 总结与展望1

详解nginx 中location和 proxy_pass的匹配规则

《详解nginx中location和proxy_pass的匹配规则》location是Nginx中用来匹配客户端请求URI的指令,决定如何处理特定路径的请求,它定义了请求的路由规则,后续的配置(如... 目录location 的作用语法示例:location /www.chinasem.cntestproxy

使用Python实现一键隐藏屏幕并锁定输入

《使用Python实现一键隐藏屏幕并锁定输入》本文主要介绍了使用Python编写一个一键隐藏屏幕并锁定输入的黑科技程序,能够在指定热键触发后立即遮挡屏幕,并禁止一切键盘鼠标输入,这样就再也不用担心自己... 目录1. 概述2. 功能亮点3.代码实现4.使用方法5. 展示效果6. 代码优化与拓展7. 总结1.