脚本全局变量更优设置方案?优化doLotsOfStuff函数调用可读性
全局变量零散使用很容易导致代码混乱、难以维护,这里分享几个更优雅的替代方案:
用配置类集中封装
把所有相关配置变量放到一个类里(推荐用dataclasses.dataclass简化定义),既避免命名空间污染,又能统一管理配置,还能加参数验证逻辑。比如:from dataclasses import dataclass @dataclass class AppConfig: MAX_RETRY_TIMES: int = 3 API_BASE_URL: str = "https://api.example.com" DEBUG_MODE: bool = False def __post_init__(self): # 可在这里添加参数合法性检查 if self.MAX_RETRY_TIMES < 1: raise ValueError("MAX_RETRY_TIMES must be at least 1") # 初始化全局配置实例 config = AppConfig() # 使用时直接通过实例访问 if config.DEBUG_MODE: print("Debug mode activated")这种方式配置结构清晰,修改和调试都很方便,还支持完整的类型提示。
用单独模块存放配置
如果项目较小,不想折腾类,可以把所有配置变量放到单独的模块(比如config.py)里,再在其他脚本中导入使用。相当于把全局变量隔离在一个模块中,避免和业务代码混在一起:# config.py MAX_RETRY_TIMES = 3 API_BASE_URL = "https://api.example.com" # main.py import config print(f"Connecting to API: {config.API_BASE_URL}")这种方式简单直接,适合快速开发的小型项目。
注意:尽量避免直接使用无封装的全局变量——它们很容易被意外修改,排查问题时会非常头疼。
调用doLotsOfStuff时参数太多导致代码行过长?这几个方法能快速提升可读性:
关键字参数换行
这是最简单的方案,不用修改函数定义,只需要把每个关键字参数单独占一行:doLotsOfStuff( user_authentication_token=auth_token, database_connection_string=db_conn_str, max_concurrent_requests=max_req, timeout_seconds=30, log_file_path="/var/log/app.log" )每个参数清晰可见,一眼就能看懂每个值对应的参数名,维护起来也方便。
打包参数为字典,用
**解包传递
如果这些参数需要重复使用(比如多次调用doLotsOfStuff),可以先整理到一个字典里,再用**解包传递给函数:# 提前整理参数字典 stuff_args = { "user_authentication_token": auth_token, "database_connection_string": db_conn_str, "max_concurrent_requests": max_req, "timeout_seconds": 30, "log_file_path": "/var/log/app.log" } # 简洁调用函数 doLotsOfStuff(**stuff_args)这种方式不仅缩短了调用行,还能统一管理参数,后续修改参数时只需要改字典即可。
让函数接受配置对象
如果这个函数是项目中常用的,建议修改函数定义,让它接受一个配置类的实例(和第一个问题的思路呼应)。这样调用时只需要传一个对象,代码更简洁,还能获得完整的类型提示:# 先定义参数类 from dataclasses import dataclass @dataclass class StuffParams: user_authentication_token: str database_connection_string: str max_concurrent_requests: int timeout_seconds: int log_file_path: str # 修改doLotsOfStuff函数 def doLotsOfStuff(params: StuffParams): # 使用参数时直接通过params访问 print(f"Using log file: {params.log_file_path}") # 调用时创建参数实例 params = StuffParams( user_authentication_token=auth_token, database_connection_string=db_conn_str, max_concurrent_requests=max_req, timeout_seconds=30, log_file_path="/var/log/app.log" ) doLotsOfStuff(params)这种方式适合长期维护的项目,能避免参数顺序错误,还让函数的参数结构更清晰。
内容的提问来源于stack exchange,提问作者Mohammad Athar

