在python开发中,编写可重用的工具类和通用的异常处理机制是提高代码质量和开发效率的关键。本文将介绍如何将特定的异常类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_path: 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 = 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.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)
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文件路径
: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 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通用工具类与异常处理内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论