You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python全局变量替代方案:代码空白行检查程序优化问询

无全局变量的过程式实现

可以通过两种过程式风格的方式重构代码,彻底消除全局变量的使用:


方式一:主循环维护局部状态

把空白行计数器作为主循环的局部变量,逻辑内聚且直观:

import re

def is_blank_line(line):
    return re.match(r'^\s*$', line) is not None

with open('input_file.py', 'r', encoding='utf-8') as f:
    blank_lines_counter = 0
    for line_num, line in enumerate(f, 1):
        if is_blank_line(line):
            blank_lines_counter += 1
        else:
            if blank_lines_counter > 2:
                print(f'Line {line_num}: More than two blank lines used before this line')
            blank_lines_counter = 0

改进说明

  • 将空白行判断逻辑抽为独立小函数is_blank_line,主循环逻辑更清晰
  • 计数器仅在循环范围内可见,避免全局状态污染
  • 直接遍历文件对象,无需一次性加载所有行,处理大文件更高效

方式二:闭包封装状态

用闭包把计数器封装在函数内部,既保留逻辑独立性,又避免全局变量:

import re

def create_blank_line_checker():
    blank_lines_counter = 0
    def checker(line):
        nonlocal blank_lines_counter
        if re.match(r'^\s*$', line):
            blank_lines_counter += 1
            return False
        else:
            exceeded = blank_lines_counter > 2
            blank_lines_counter = 0
            return exceeded
    return checker

with open('input_file.py', 'r', encoding='utf-8') as f:
    check_blank_lines = create_blank_line_checker()
    for line_num, line in enumerate(f, 1):
        if check_blank_lines(line):
            print(f'Line {line_num}: More than two blank lines used before this line')

闭包方式优势

  • 计数器状态被封闭在闭包内部,外部无法随意修改,状态更安全
  • 检查逻辑可复用,主循环代码更简洁

内容的提问来源于stack exchange,提问作者Maxim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 20:50:12