最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

詳解Python中通用工具類與異常處理

 更新時(shí)間:2024年12月28日 10:40:11   作者:engchina  
在Python開發(fā)中,編寫可重用的工具類和通用的異常處理機(jī)制是提高代碼質(zhì)量和開發(fā)效率的關(guān)鍵,本文將介紹如何將特定的異常類改寫為更通用的ValidationException,并創(chuàng)建一個(gè)通用的工具類Utils,需要的可以參考下

在Python開發(fā)中,編寫可重用的工具類和通用的異常處理機(jī)制是提高代碼質(zhì)量和開發(fā)效率的關(guān)鍵。本文將介紹如何將特定的異常類GlueValidaionException改寫為更通用的ValidationException,并創(chuàng)建一個(gè)通用的工具類Utils,包含常用的文件操作和數(shù)據(jù)處理方法。最后,我們將通過代碼示例展示如何使用這些工具。

1. 通用異常類:ValidationException

首先,我們將GlueValidaionException改寫為更通用的ValidationException,使其適用于各種驗(yàn)證場景。

class ValidationException(Exception):
    """
    通用驗(yàn)證異常類,適用于各種驗(yàn)證場景。
    """
    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

接下來,我們創(chuàng)建一個(gè)通用的工具類Utils,包含常用的文件操作和數(shù)據(jù)處理方法。

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文件轉(zhuǎn)換為字典。
        
        :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文件語法錯(cuò)誤: {file_path}", e)
        return parsed_dict

    @staticmethod
    def yaml_to_class(yaml_file_path: str, cls: type, default_yaml_file_path: str = None):
        """
        將YAML文件轉(zhuǎn)換為類對象。
        
        :param yaml_file_path: YAML文件路徑
        :param cls: 目標(biāo)類
        :param default_yaml_file_path: 默認(rèn)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文件轉(zhuǎn)換為類失敗: {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 = 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文件讀取錯(cuò)誤: {file_path}. 錯(cuò)誤: {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. 示例文件內(nèi)容

以下是示例文件的內(nèi)容,包括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文件轉(zhuǎn)換為字典
yaml_dict = Utils.yaml_to_dict("config.yaml")
print("YAML文件轉(zhuǎn)換為字典:", yaml_dict)

# 示例2: 將YAML文件轉(zhuǎn)換為類對象
config_obj = Utils.yaml_to_class("config.yaml", Config, "default_config.yaml")
print("YAML文件轉(zhuǎn)換為類對象:", 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("追加數(shù)據(jù)到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. 運(yùn)行結(jié)果

運(yùn)行上述代碼后,輸出結(jié)果如下:

YAML文件轉(zhuǎn)換為字典: {'name': 'custom_name', 'value': 200}
YAML文件轉(zhuǎn)換為類對象: 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}
追加數(shù)據(jù)到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):
    """
    通用驗(yàn)證異常類,適用于各種驗(yàn)證場景。
    """

    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文件轉(zhuǎn)換為字典。

        :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文件語法錯(cuò)誤: {file_path}", e)
        return parsed_dict

    @staticmethod
    def yaml_to_class(yaml_file_path: str, cls: type, default_yaml_file_path: str = None):
        """
        將YAML文件轉(zhuǎn)換為類對象。

        :param yaml_file_path: YAML文件路徑
        :param cls: 目標(biāo)類
        :param default_yaml_file_path: 默認(rèn)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文件轉(zhuǎn)換為類失敗: {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文件讀取錯(cuò)誤: {file_path}. 錯(cuò)誤: {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文件轉(zhuǎn)換為字典
yaml_dict = Utils.yaml_to_dict("config.yaml")
print("YAML文件轉(zhuǎn)換為字典:", yaml_dict)

# 示例2: 將YAML文件轉(zhuǎn)換為類對象
config_obj = Utils.yaml_to_class("config.yaml", Config, "default_config.yaml")
print("YAML文件轉(zhuǎn)換為類對象:", 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("追加數(shù)據(jù)到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. 總結(jié)

通過將特定的異常類改寫為通用的ValidationException,并創(chuàng)建一個(gè)包含常用方法的Utils工具類,我們可以大大提高代碼的復(fù)用性和可維護(hù)性。本文提供的代碼示例展示了如何使用這些工具類進(jìn)行文件操作和數(shù)據(jù)處理,適合初級Python程序員學(xué)習(xí)和參考。

到此這篇關(guān)于詳解Python中通用工具類與異常處理的文章就介紹到這了,更多相關(guān)Python通用工具類與異常處理內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • PyQt5重寫QComboBox的鼠標(biāo)點(diǎn)擊事件方法

    PyQt5重寫QComboBox的鼠標(biāo)點(diǎn)擊事件方法

    今天小編就為大家分享一篇PyQt5重寫QComboBox的鼠標(biāo)點(diǎn)擊事件方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-06-06
  • Python實(shí)現(xiàn)將字典(列表按列)存入csv文件

    Python實(shí)現(xiàn)將字典(列表按列)存入csv文件

    這篇文章主要介紹了Python實(shí)現(xiàn)將字典(列表按列)存入csv文件方式,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-06-06
  • Python基于similarities實(shí)現(xiàn)文本語義相似度計(jì)算和文本匹配搜索

    Python基于similarities實(shí)現(xiàn)文本語義相似度計(jì)算和文本匹配搜索

    similarities?實(shí)現(xiàn)了多種相似度計(jì)算、匹配搜索算法,支持文本、圖像,python3開發(fā),下面我們就來看看如何使用similarities實(shí)現(xiàn)文本語義相似度計(jì)算和文本匹配搜索吧
    2024-03-03
  • Python調(diào)用另一個(gè)py文件并傳遞參數(shù)常見的方法及其應(yīng)用場景

    Python調(diào)用另一個(gè)py文件并傳遞參數(shù)常見的方法及其應(yīng)用場景

    這篇文章主要介紹了在Python中調(diào)用另一個(gè)py文件并傳遞參數(shù)的幾種常見方法,包括使用import語句、exec函數(shù)、subprocess模塊、os.system函數(shù)以及argparse模塊,每種方法都有其適用場景和優(yōu)缺點(diǎn),需要的朋友可以參考下
    2025-01-01
  • 解決python列表list中的截取問題

    解決python列表list中的截取問題

    這篇文章主要介紹了解決python列表list中的截取問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-05-05
  • python填充彩色圖形的實(shí)現(xiàn)示例

    python填充彩色圖形的實(shí)現(xiàn)示例

    本文主要介紹了python填充彩色圖形的實(shí)現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-04-04
  • python serial串口通信示例詳解

    python serial串口通信示例詳解

    Python的serial庫是一個(gè)用于串口通信的強(qiáng)大工具,它提供了一個(gè)簡單而靈活的接口,可以方便地與串口設(shè)備進(jìn)行通信,包括與驅(qū)動電機(jī)進(jìn)行通信,這篇文章主要介紹了python serial串口通信,需要的朋友可以參考下
    2023-12-12
  • python實(shí)現(xiàn)對數(shù)組按指定列排序

    python實(shí)現(xiàn)對數(shù)組按指定列排序

    這篇文章主要介紹了python實(shí)現(xiàn)對數(shù)組按指定列排序方式,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-02-02
  • python實(shí)現(xiàn)高斯(Gauss)迭代法的例子

    python實(shí)現(xiàn)高斯(Gauss)迭代法的例子

    今天小編就為大家分享一篇python實(shí)現(xiàn)高斯(Gauss)迭代法的例子,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-11-11
  • Pycharm安裝第三方庫時(shí)Non-zero exit code錯(cuò)誤解決辦法

    Pycharm安裝第三方庫時(shí)Non-zero exit code錯(cuò)誤解決辦法

    這篇文章主要介紹了Pycharm安裝第三方庫時(shí)Non-zero exit code錯(cuò)誤解決辦法,最好的解決辦法可以通過“Pycharm”左下角的“Terminal”,在pycharm內(nèi)使用pip安裝,以安裝“requests”為例,需要的朋友可以參考下
    2023-01-01

最新評論

剑河县| 东城区| 满洲里市| 丰原市| 太仆寺旗| 靖江市| 莆田市| 上虞市| 扬中市| 焉耆| 水城县| 康定县| 紫金县| 莆田市| 科尔| 兴仁县| 广饶县| 马边| 禹城市| 江华| 阳新县| 交城县| 和田县| 德江县| 大城县| 固始县| 定边县| 绍兴县| 凌云县| 赤城县| 随州市| 勐海县| 体育| 吕梁市| 云浮市| 长阳| 天门市| 区。| 津南区| 炉霍县| 都兰县|