python函数降低编程复杂度_Python重构此函数,将其认知复杂度从19降低到允许的15...

博客内容介绍了如何通过提取函数、统一异常处理和创建文件扩展名处理器来简化Python代码,从而降低函数的认知复杂度。首先,定义了获取文件路径的函数`_file_paths`,接着实现异常处理函数`_translate_error`。然后,创建了处理不同文件类型的函数如`_handle_cfn`和`_handle_tf`。对于不匹配的文件扩展名,使用`_null_handler`进行处理。最后,将所有这些组件整合到`file_handler`函数中,实现了按文件扩展名调用相应处理函数的功能。
摘要由CSDN通过智能技术生成

提取函数以生成文件路径:def _file_paths(directory):

for root, dirs, filenames in os.walk(directory):

for filename in filenames:

file_path = os.path.join(root, filename)

if os.path.isfile(file_path):

yield file_path

统一异常处理:

^{pr2}$

提取用于处理文件类型的函数:def _handle_cfn(file_object):

file_contents = file_object.read()

if "AWSTemplateFormatVersion" in file_contents:

data = json.dumps(file_contents)

print(data)

def _handle_tf(file_object):

obj = hcl.load(file_oject)

data = json.dumps(obj)

print(data)

为文件扩展名不匹配时创建空处理程序:def _null_handler(file_object):

pass

将文件扩展名映射到处理程序:_extension_handlers = {'.json': _handle_cfn,

'.template': _handle_cfn,

'.yaml': _handle_cfn,

'.yml': _handle_cfn,

'.tf': _handle_tf}

组合起来:import os

import json

import click

import hcl

def file_handler(dir):

for file_path in _file_paths(dir):

base, extension = os.path.splitext(file_path)

handler = _extension_handlers.get(extension, _null_handler)

with open(file_path) as file_object:

with _translate_error(ValueError, SystemExit):

handler(file_object)

您可以进一步提取一个用于处理每个文件的函数:def _handle_file(file_path):

base, extension = os.path.splitext(file_path)

handler = _extension_handlers.get(extension, _null_handler)

with open(file_path) as file_object:

with _translate_error(ValueError, SystemExit):

handler(file_object)

那么您的主要功能是:def file_handler(dir):

for file_path in _file_paths(dir):

_handle_file(file_path)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值