Python中UnboundLocalError报错修复:无法访问未赋值局部变量
修复UnboundLocalError错误方案
错误原因
你代码里的last_month变量仅在len(str(d.month)) == 1的条件分支中被赋值,当输入日期的月份是两位数(比如测试用的10月)时,该条件不成立,last_month未被初始化,后续拼接字符串时就会触发UnboundLocalError。
修复方法
无需额外判断月份位数,直接用格式化字符串统一处理月份的补零需求,或者直接构造日期对象再格式化,避免手动拼接字符串的风险。
方案1:用f-string格式化构造最后一天日期
import datetime import calendar def calendar_days_month(run_date): """ :param run_date: date on which the process is running :return: tuple of first and last calendar day of the month, formatted as 'YYYY-MM-DD' """ d = datetime.datetime.strptime(run_date, '%Y-%m-%d').date() first_calendar_day = d.replace(day=1).strftime("%Y-%m-%d") last_day_num = calendar.monthrange(d.year, d.month)[1] # 用f-string自动补零,无需判断月份位数 last_calendar_day = f"{d.year}-{d.month:02d}-{last_day_num:02d}" return first_calendar_day, last_calendar_day abc_date = '2024-10-31' test_1, test_2 = calendar_days_month(abc_date) print(test_2) # 输出 2024-10-31 print(test_1) # 输出 2024-10-01
方案2:构造日期对象再格式化(更推荐)
直接用replace方法修改日期的day属性为当月最后一天,再格式化字符串,完全避免手动拼接:
import datetime import calendar def calendar_days_month(run_date): """ :param run_date: date on which the process is running :return: tuple of first and last calendar day of the month, formatted as 'YYYY-MM-DD' """ d = datetime.datetime.strptime(run_date, '%Y-%m-%d').date() first_calendar_day = d.replace(day=1).strftime("%Y-%m-%d") last_day_num = calendar.monthrange(d.year, d.month)[1] # 构造最后一天的date对象,再格式化 last_calendar_day = d.replace(day=last_day_num).strftime("%Y-%m-%d") return first_calendar_day, last_calendar_day abc_date = '2024-10-31' test_1, test_2 = calendar_days_month(abc_date) print(test_2) # 输出 2024-10-31 print(test_1) # 输出 2024-10-01
额外说明
两种方案都解决了变量未初始化的问题,同时让代码更简洁易维护。方案2利用datetime库的原生方法处理日期,避免了手动拼接字符串可能出现的格式错误,是更稳妥的选择。
内容的提问来源于stack exchange,提问作者nmr
相关产品推荐
相关产品推荐

