|
27 | 27 | error = ValueError |
28 | 28 |
|
29 | 29 | # Exceptions raised for bad input |
30 | | -class IllegalMonthError(ValueError): |
| 30 | +# This is trick for backward compatibility. Since 3.13, we will raise IllegalMonthError instead of |
| 31 | +# IndexError for bad month number(out of 1-12). But we can't remove IndexError for backward compatibility. |
| 32 | +class IllegalMonthError(ValueError, IndexError): |
31 | 33 | def __init__(self, month): |
32 | 34 | self.month = month |
33 | 35 | def __str__(self): |
@@ -158,11 +160,14 @@ def weekday(year, month, day): |
158 | 160 | return Day(datetime.date(year, month, day).weekday()) |
159 | 161 |
|
160 | 162 |
|
| 163 | +def _validate_month(month): |
| 164 | + if not 1 <= month <= 12: |
| 165 | + raise IllegalMonthError(month) |
| 166 | + |
161 | 167 | def monthrange(year, month): |
162 | 168 | """Return weekday of first day of month (0-6 ~ Mon-Sun) |
163 | 169 | and number of days (28-31) for year, month.""" |
164 | | - if not 1 <= month <= 12: |
165 | | - raise IllegalMonthError(month) |
| 170 | + _validate_month(month) |
166 | 171 | day1 = weekday(year, month, 1) |
167 | 172 | ndays = mdays[month] + (month == FEBRUARY and isleap(year)) |
168 | 173 | return day1, ndays |
@@ -370,6 +375,8 @@ def formatmonthname(self, theyear, themonth, width, withyear=True): |
370 | 375 | """ |
371 | 376 | Return a formatted month name. |
372 | 377 | """ |
| 378 | + _validate_month(themonth) |
| 379 | + |
373 | 380 | s = month_name[themonth] |
374 | 381 | if withyear: |
375 | 382 | s = "%s %r" % (s, theyear) |
@@ -500,6 +507,7 @@ def formatmonthname(self, theyear, themonth, withyear=True): |
500 | 507 | """ |
501 | 508 | Return a month name as a table row. |
502 | 509 | """ |
| 510 | + _validate_month(themonth) |
503 | 511 | if withyear: |
504 | 512 | s = '%s %s' % (month_name[themonth], theyear) |
505 | 513 | else: |
@@ -786,6 +794,8 @@ def main(args=None): |
786 | 794 | if options.month is None: |
787 | 795 | optdict["c"] = options.spacing |
788 | 796 | optdict["m"] = options.months |
| 797 | + if options.month is not None: |
| 798 | + _validate_month(options.month) |
789 | 799 | if options.year is None: |
790 | 800 | result = cal.formatyear(datetime.date.today().year, **optdict) |
791 | 801 | elif options.month is None: |
|
0 commit comments