-
-
Notifications
You must be signed in to change notification settings - Fork 701
Expand file tree
/
Copy pathholiday_base.py
More file actions
1473 lines (1209 loc) · 55.2 KB
/
Copy pathholiday_base.py
File metadata and controls
1473 lines (1209 loc) · 55.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# holidays
# --------
# A fast, efficient Python library for generating country, province and state
# specific sets of holidays on the fly. It aims to make determining whether a
# specific date is a holiday as fast and flexible as possible.
#
# Authors: Vacanza Team and individual contributors (see CONTRIBUTORS file)
# dr-prodigy <dr.prodigy.github@gmail.com> (c) 2017-2023
# ryanss <ryanssdev@icloud.com> (c) 2014-2017
# Website: https://github.com/vacanza/holidays
# License: MIT (see LICENSE file)
__all__ = ("DateLike", "HolidayBase", "HolidaySum")
import copy
import warnings
from bisect import bisect_left, bisect_right
from calendar import isleap
from collections.abc import Iterable
from datetime import date, datetime, timedelta, timezone
from functools import cached_property
from gettext import gettext, translation
from pathlib import Path
from typing import Any, Literal, Union, cast
from dateutil.parser import parse
from holidays.calendars.gregorian import (
MON,
TUE,
WED,
THU,
FRI,
SAT,
SUN,
_timedelta,
_get_nth_weekday_from,
_get_nth_weekday_of_month,
DAYS,
MONTHS,
WEEKDAYS,
)
from holidays.constants import HOLIDAY_NAME_DELIMITER, PUBLIC, DEFAULT_START_YEAR, DEFAULT_END_YEAR
from holidays.helpers import _normalize_arguments, _normalize_tuple
CategoryArg = str | Iterable[str]
DateArg = date | tuple[int, int] | tuple[int, int, int]
DateLike = date | datetime | str | float | int
NameLookup = Literal["contains", "exact", "startswith", "icontains", "iexact", "istartswith"]
SpecialHoliday = tuple[int, int, str] | tuple[tuple[int, int, str], ...]
SubstitutedHoliday = (
tuple[int, int, int, int]
| tuple[int, int, int, int, int]
| tuple[tuple[int, int, int, int] | tuple[int, int, int, int, int], ...]
)
YearArg = int | Iterable[int]
class HolidayBase(dict[date, str]):
"""Represent a dictionary-like collection of holidays for a specific country or region.
This class inherits from `dict` and maps holiday dates to their names. It supports
customization by country and, optionally, by province or state (subdivision). A date
not present as a key is not considered a holiday (or, if `observed` is `False`, not
considered an observed holiday).
Keys are holiday dates, and values are corresponding holiday names. When accessing or
assigning holidays by date, the following input formats are accepted:
* `datetime.date`
* `datetime.datetime`
* `float` or `int` (Unix timestamp)
* `str` of any format recognized by `dateutil.parser.parse()`
Keys are always returned as `datetime.date` objects.
To maximize performance, the holiday list is lazily populated one year at a time.
On instantiation, the object is empty. Once a date is accessed, the full calendar
year for that date is generated, unless `expand` is set to `False`. To pre-populate
holidays, instantiate the class with the `years` argument:
us_holidays = holidays.US(years=2020)
It is recommended to use the
[country_holidays()][holidays.utils.country_holidays] function for instantiation.
Example usage:
>>> from holidays import country_holidays
>>> us_holidays = country_holidays('US')
# For a specific subdivisions (e.g. state or province):
>>> california_holidays = country_holidays('US', subdiv='CA')
The below will cause 2015 holidays to be calculated on the fly:
>>> from datetime import date
>>> assert date(2015, 1, 1) in us_holidays
This will be faster because 2015 holidays are already calculated:
>>> assert date(2015, 1, 2) not in us_holidays
The [`HolidayBase`][holidays.holiday_base.HolidayBase] class also recognizes strings
of many formats and numbers representing a POSIX timestamp:
>>> assert '2014-01-01' in us_holidays
>>> assert '1/1/2014' in us_holidays
>>> assert 1388597445 in us_holidays
Show the holiday's name:
>>> us_holidays.get('2014-01-01')
"New Year's Day"
Check a range:
>>> us_holidays['2014-01-01': '2014-01-03']
[datetime.date(2014, 1, 1)]
List all 2020 holidays:
>>> us_holidays = country_holidays('US', years=2020)
>>> for day in sorted(us_holidays.items()):
... print(day)
(datetime.date(2020, 1, 1), "New Year's Day")
(datetime.date(2020, 1, 20), 'Martin Luther King Jr. Day')
(datetime.date(2020, 2, 17), "Washington's Birthday")
(datetime.date(2020, 5, 25), 'Memorial Day')
(datetime.date(2020, 7, 3), 'Independence Day (observed)')
(datetime.date(2020, 7, 4), 'Independence Day')
(datetime.date(2020, 9, 7), 'Labor Day')
(datetime.date(2020, 10, 12), 'Columbus Day')
(datetime.date(2020, 11, 11), 'Veterans Day')
(datetime.date(2020, 11, 26), 'Thanksgiving Day')
(datetime.date(2020, 12, 25), 'Christmas Day')
Some holidays are only present in parts of a country:
>>> us_pr_holidays = country_holidays('US', subdiv='PR')
>>> assert '2018-01-06' not in us_holidays
>>> assert '2018-01-06' in us_pr_holidays
Append custom holiday dates by passing one of the following:
* A dict mapping date values to holiday names (e.g. `{'2010-07-10': 'My birthday!'}`).
* A list of date values (`datetime.date`, `datetime.datetime`, `str`, `int`, or `float`);
each will be added with 'Holiday' as the default name.
* A single date value of any of the supported types above; 'Holiday' will be used as
the default name.
```python
>>> custom_holidays = country_holidays('US', years=2015)
>>> custom_holidays.update({'2015-01-01': "New Year's Day"})
>>> custom_holidays.update(['2015-07-01', '07/04/2015'])
>>> custom_holidays.update(date(2015, 12, 25))
>>> assert date(2015, 1, 1) in custom_holidays
>>> assert date(2015, 1, 2) not in custom_holidays
>>> assert '12/25/2015' in custom_holidays
```
For special (one-off) country-wide holidays handling use
`special_public_holidays`:
special_public_holidays = {
1977: ((JUN, 7, "Silver Jubilee of Elizabeth II"),),
1981: ((JUL, 29, "Wedding of Charles and Diana"),),
1999: ((DEC, 31, "Millennium Celebrations"),),
2002: ((JUN, 3, "Golden Jubilee of Elizabeth II"),),
2011: ((APR, 29, "Wedding of William and Catherine"),),
2012: ((JUN, 5, "Diamond Jubilee of Elizabeth II"),),
2022: (
(JUN, 3, "Platinum Jubilee of Elizabeth II"),
(SEP, 19, "State Funeral of Queen Elizabeth II"),
),
}
def _populate(self, year):
super()._populate(year)
...
For more complex logic, like 4th Monday of January, you can inherit the
[`HolidayBase`][holidays.holiday_base.HolidayBase] class and define your own `_populate()`
method.
See documentation for examples.
"""
country: str
"""The country's ISO 3166-1 alpha-2 code."""
market: str
"""The market's ISO 3166-1 alpha-2 code."""
subdivisions: tuple[str, ...] = ()
"""The subdivisions supported for this country (see documentation)."""
subdivisions_aliases: dict[str, str] = {}
"""Aliases for the ISO 3166-2 subdivision codes with the key as alias and
the value the ISO 3166-2 subdivision code."""
years: set[int]
"""The years calculated."""
expand: bool
"""Whether the entire year is calculated when one date from that year
is requested."""
observed: bool
"""Whether dates when public holiday are observed are included."""
subdiv: str | None = None
"""The subdiv requested as ISO 3166-2 code or one of the aliases."""
special_holidays: dict[int, SpecialHoliday | SubstitutedHoliday] = {}
"""A list of the country-wide special (as opposite to regular) holidays for
a specific year."""
_deprecated_subdivisions: tuple[str, ...] = ()
"""Other subdivisions whose names are deprecated or aliases of the official
ones."""
weekend: set[int] = {SAT, SUN}
"""Country weekend days."""
weekend_workdays: set[date]
"""Working days moved to weekends."""
default_category: str = PUBLIC
"""The entity category used by default."""
default_language: str | None = None
"""The entity language used by default."""
categories: set[str] = set()
"""Requested holiday categories."""
supported_categories: tuple[str, ...] = (PUBLIC,)
"""All holiday categories supported by this entity."""
supported_languages: tuple[str, ...] = ()
"""All languages supported by this entity."""
start_year: int = DEFAULT_START_YEAR
"""Start year of holidays presence for this entity."""
end_year: int = DEFAULT_END_YEAR
"""End year of holidays presence for this entity."""
parent_entity: type["HolidayBase"] | None = None
"""Optional parent entity to reference as a base."""
def __init__(
self,
years: YearArg | None = None,
expand: bool = True,
observed: bool = True,
subdiv: str | None = None,
prov: str | None = None, # Deprecated.
state: str | None = None, # Deprecated.
language: str | None = None,
categories: CategoryArg | None = None,
) -> None:
"""
Args:
years:
The year(s) to pre-calculate public holidays for at instantiation.
expand:
Whether the entire year is calculated when one date from that year
is requested.
observed:
Whether to include the dates when public holiday are observed
(e.g. a holiday falling on a Sunday being observed the
following Monday). This doesn't work for all countries.
subdiv:
The subdivision (e.g. state or province) as a ISO 3166-2 code
or its alias; not implemented for all countries (see documentation).
prov:
*deprecated* use `subdiv` instead.
state:
*deprecated* use `subdiv` instead.
language:
Specifies the language in which holiday names are returned.
Accepts either:
* A two-letter ISO 639-1 language code (e.g., 'en' for English, 'fr' for French),
or
* A language and entity combination using an underscore (e.g., 'en_US' for U.S.
English, 'pt_BR' for Brazilian Portuguese).
!!! warning
The provided language or locale code must be supported by the holiday
entity. Unsupported values will result in names being shown in the entity's
original language.
If not explicitly set (`language=None`), the system attempts to infer the
language from the environment's locale settings. The following environment
variables are checked, in order of precedence: LANGUAGE, LC_ALL, LC_MESSAGES, LANG.
If none of these are set or they are empty, holiday names will default to the
original language of the entity's holiday implementation.
!!! warning
This fallback mechanism may yield inconsistent results across environments
(e.g., between a terminal session and a Jupyter notebook).
To ensure consistent behavior, it is recommended to set the language parameter
explicitly. If the specified language is not supported, holiday names will remain
in the original language of the entity's holiday implementation.
This behavior will be updated and formalized in v1.
categories:
Requested holiday categories.
"""
super().__init__()
# Categories validation.
if self.default_category and self.default_category not in self.supported_categories:
raise ValueError("The default category must be listed in supported categories.")
if not self.default_category and not categories:
raise ValueError("Categories cannot be empty if `default_category` is not set.")
categories = _normalize_arguments(str, categories) or {self.default_category}
if unknown_categories := categories.difference( # type: ignore[union-attr]
self.supported_categories
):
raise ValueError(f"Category is not supported: {', '.join(unknown_categories)}.")
# Subdivision validation.
if subdiv := subdiv or prov or state:
# Handle subdivisions passed as integers.
if isinstance(subdiv, int):
subdiv = str(subdiv)
subdivision_aliases = tuple(self.subdivisions_aliases)
supported_subdivisions = set(
self.subdivisions
+ subdivision_aliases
+ self._deprecated_subdivisions
+ (self.parent_entity.subdivisions if self.parent_entity else ())
)
# Unsupported subdivisions.
if not isinstance(self, HolidaySum) and subdiv not in supported_subdivisions:
raise NotImplementedError(
f"Entity `{self._entity_code}` does not have subdivision {subdiv}"
)
# Deprecated arguments.
if prov_state := prov or state:
warnings.warn(
f"Arguments prov and state are deprecated, use subdiv='{prov_state}' instead.",
DeprecationWarning,
)
# Deprecated subdivisions.
if subdiv in self._deprecated_subdivisions:
warnings.warn(
"This subdivision is deprecated and will be removed after "
"Dec, 1 2023. The list of supported subdivisions: "
f"{', '.join(sorted(self.subdivisions))}; "
"the list of supported subdivisions aliases: "
f"{', '.join(sorted(subdivision_aliases))}.",
DeprecationWarning,
)
# Special holidays validation.
if (has_substituted_holidays := getattr(self, "has_substituted_holidays", False)) and (
not getattr(self, "substituted_label", None)
or not getattr(self, "substituted_date_format", None)
):
raise ValueError(
f"Entity `{self._entity_code}` class must have `substituted_label` "
"and `substituted_date_format` attributes set."
)
self.categories = categories
self.expand = expand
self.has_special_holidays = getattr(self, "has_special_holidays", False)
self.has_substituted_holidays = has_substituted_holidays
self.language = language
self.observed = observed
self.subdiv = subdiv
self.weekend_workdays = getattr(self, "weekend_workdays", set())
self.years = _normalize_arguments(int, years)
# Configure l10n related attributes.
self._init_translation()
# Populate holidays.
for year in self.years:
self._populate(year)
def __add__(
self, other: Union[int, "HolidayBase", "HolidaySum"]
) -> "HolidayBase | HolidaySum":
"""Add another dictionary of public holidays creating a
[`HolidaySum`][holidays.holiday_base.HolidaySum] object.
Args:
other:
The dictionary of public holiday to be added.
Returns:
A [`HolidaySum`][holidays.holiday_base.HolidaySum]
instance representing the combined holidays,
or the original object if no combination occurs.
Raises:
TypeError:
If `other` is not a `HolidayBase` or `HolidaySum`.
"""
if isinstance(other, int) and other == 0:
# Required to sum() list of holidays
# sum([h1, h2]) is equivalent to (0 + h1 + h2).
return self
if not isinstance(other, (HolidayBase, HolidaySum)):
raise TypeError("Holiday objects can only be added with other Holiday objects")
return HolidaySum(self, other)
def __bool__(self) -> bool:
return len(self) > 0
def __contains__(self, key: object) -> bool:
"""Check if a given date is a holiday.
The method supports the following input types:
* `datetime.date`
* `datetime.datetime`
* `float` or `int` (Unix timestamp)
* `str` of any format recognized by `dateutil.parser.parse()`
Args:
key:
The date to check.
Returns:
`True` if the date is a holiday, `False` otherwise.
"""
if not isinstance(key, (date, datetime, float, int, str)):
raise TypeError(f"Cannot convert type '{type(key)}' to date.")
return dict.__contains__(cast("dict[Any, Any]", self), self.__keytransform__(key))
def __eq__(self, other: object) -> bool:
if not isinstance(other, HolidayBase):
return False
for attribute_name in self.__attribute_names:
if getattr(self, attribute_name, None) != getattr(other, attribute_name, None):
return False
return dict.__eq__(cast("dict[Any, Any]", self), other)
def __getattr__(self, name):
try:
return self.__getattribute__(name)
except AttributeError as e:
# This part is responsible for _add_holiday_* syntactic sugar support.
add_holiday_prefix = "_add_holiday_"
# Raise early if prefix doesn't match to avoid patterns checks.
if name[: len(add_holiday_prefix)] != add_holiday_prefix:
raise e
tokens = name.split("_")
# Handle <month> <day> patterns (e.g., _add_holiday_jun_15()).
if len(tokens) == 5:
*_, month, day = tokens
if month in MONTHS and day in DAYS:
return lambda name: self._add_holiday(
name, date(self._year, MONTHS[month], int(day))
)
elif len(tokens) == 7:
# Handle <last/nth> <weekday> of <month> patterns (e.g.,
# _add_holiday_last_mon_of_aug() or _add_holiday_3rd_fri_of_aug()).
*_, number, weekday, of, month = tokens
if (
of == "of"
and (number == "last" or number[0].isdigit())
and month in MONTHS
and weekday in WEEKDAYS
):
return lambda name: self._add_holiday(
name,
_get_nth_weekday_of_month(
-1 if number == "last" else int(number[0]),
WEEKDAYS[weekday],
MONTHS[month],
self._year,
),
)
# Handle <n> days <past/prior> easter patterns (e.g.,
# _add_holiday_8_days_past_easter() or
# _add_holiday_5_days_prior_easter()).
*_, days, unit, delta_direction, easter = tokens
if (
unit in {"day", "days"}
and delta_direction in {"past", "prior"}
and easter == "easter"
and len(days) < 3
and days.isdigit()
):
return lambda name: self._add_holiday(
name,
_timedelta(
self._easter_sunday,
+int(days) if delta_direction == "past" else -int(days),
),
)
# Handle <n> day(s) <past/prior> <last/<nth> <weekday> of <month> patterns (e.g.,
# _add_holiday_1_day_past_1st_fri_of_aug() or
# _add_holiday_5_days_prior_last_fri_of_aug()).
elif len(tokens) == 10:
*_, days, unit, delta_direction, number, weekday, of, month = tokens
if (
unit in {"day", "days"}
and delta_direction in {"past", "prior"}
and of == "of"
and len(days) < 3
and days.isdigit()
and (number == "last" or number[0].isdigit())
and month in MONTHS
and weekday in WEEKDAYS
):
return lambda name: self._add_holiday(
name,
_timedelta(
_get_nth_weekday_of_month(
-1 if number == "last" else int(number[0]),
WEEKDAYS[weekday],
MONTHS[month],
self._year,
),
+int(days) if delta_direction == "past" else -int(days),
),
)
# Handle <nth> <weekday> <before/from> <month> <day> patterns (e.g.,
# _add_holiday_1st_mon_before_jun_15() or _add_holiday_1st_mon_from_jun_15()).
elif len(tokens) == 8:
*_, number, weekday, date_direction, month, day = tokens
if (
date_direction in {"before", "from"}
and number[0].isdigit()
and month in MONTHS
and weekday in WEEKDAYS
and day in DAYS
):
return lambda name: self._add_holiday(
name,
_get_nth_weekday_from(
-int(number[0]) if date_direction == "before" else +int(number[0]),
WEEKDAYS[weekday],
date(self._year, MONTHS[month], int(day)),
),
)
raise e # No match.
def __getitem__(self, key: DateLike) -> Any:
if isinstance(key, slice):
if not key.start or not key.stop:
raise ValueError("Both start and stop must be given.")
start = self.__keytransform__(key.start)
stop = self.__keytransform__(key.stop)
if key.step is None:
step = 1
elif isinstance(key.step, int):
step = key.step
elif isinstance(key.step, timedelta):
step = key.step.days
else:
raise TypeError(f"Cannot convert type '{type(key.step)}' to int.")
if step == 0:
raise ValueError("Step value must not be zero.")
diff_days = (stop - start).days
if diff_days < 0 <= step or diff_days >= 0 > step:
step = -step
return [
day
for delta_days in range(0, diff_days, step)
if (day := _timedelta(start, delta_days)) in self
]
return dict.__getitem__(self, self.__keytransform__(key))
def __getstate__(self) -> dict[str, Any]:
"""Return the object's state for serialization."""
state = self.__dict__.copy()
state.pop("tr", None)
return state
def __keytransform__(self, key: DateLike) -> date:
"""Convert various date-like formats to `datetime.date`.
The method supports the following input types:
* `datetime.date`
* `datetime.datetime`
* `float` or `int` (Unix timestamp)
* `str` of any format recognized by `dateutil.parser.parse()`
Args:
key:
The date-like object to convert.
Returns:
The corresponding `datetime.date` representation.
"""
dt: date | None = None
# Try to catch `date` and `str` type keys first.
# Using type() here to skip date subclasses.
# Key is `date`.
if type(key) is date:
dt = key
# Key is `str` instance.
elif isinstance(key, str):
# key possibly contains a date in YYYY-MM-DD or YYYYMMDD format.
if len(key) in {8, 10}:
try:
dt = date.fromisoformat(key)
except ValueError:
pass
if dt is None:
try:
dt = parse(key).date()
except (OverflowError, ValueError):
raise ValueError(f"Cannot parse date from string '{key}'")
# Key is `datetime` instance.
elif isinstance(key, datetime):
dt = key.date()
# Must go after the `isinstance(key, datetime)` check as datetime is `date` subclass.
elif isinstance(key, date):
dt = key
# Key is `float` or `int` instance.
elif isinstance(key, (float, int)):
dt = datetime.fromtimestamp(key, timezone.utc).date()
# Key is not supported.
else:
raise TypeError(f"Cannot convert type '{type(key)}' to date.")
# Automatically expand for `expand=True` cases.
if self.expand and dt.year not in self.years:
self.years.add(dt.year)
self._populate(dt.year)
return dt
def __ne__(self, other: object) -> bool:
if not isinstance(other, HolidayBase):
return True
for attribute_name in self.__attribute_names:
if getattr(self, attribute_name, None) != getattr(other, attribute_name, None):
return True
return dict.__ne__(self, other)
def __radd__(self, other: Any) -> "HolidayBase":
return self.__add__(other)
def __reduce__(self) -> str | tuple[Any, ...]:
return super().__reduce__()
def __repr__(self) -> str:
if self:
return super().__repr__()
if hasattr(self, "market"):
args = [repr(self.market)]
if self.language is not None:
args.append(f"language={self.language!r}")
return f"holidays.financial_holidays({', '.join(args)})"
elif hasattr(self, "country"):
args = [repr(self.country)]
if self.categories != {"public"}:
args.append(f"categories={sorted(self.categories)!r}")
if self.language is not None:
args.append(f"language={self.language!r}")
if self.subdiv:
args.append(f"subdiv={self.subdiv!r}")
return f"holidays.country_holidays({', '.join(args)})"
return "holidays.HolidayBase()"
def __setattr__(self, key: str, value: Any) -> None:
dict.__setattr__(self, key, value)
if self and key in {"categories", "observed"}:
self.clear()
for year in self.years: # Re-populate holidays for each year.
self._populate(year)
def __setitem__(self, key: DateLike, value: str) -> None:
if key in self:
# If there are multiple holidays on the same date
# order their names alphabetically.
holiday_names = set(self[key].split(HOLIDAY_NAME_DELIMITER))
holiday_names.update(value.split(HOLIDAY_NAME_DELIMITER))
value = HOLIDAY_NAME_DELIMITER.join(sorted(holiday_names))
dict.__setitem__(self, self.__keytransform__(key), value)
def __setstate__(self, state: dict[str, Any]) -> None:
"""Restore the object's state after deserialization."""
self.__dict__.update(state)
self._init_translation()
def __str__(self) -> str:
if self:
return super().__str__()
parts = (
f"'{attribute_name}': {getattr(self, attribute_name, None)}"
for attribute_name in self.__attribute_names
)
return f"{{{', '.join(parts)}}}"
@property
def __attribute_names(self):
return ("country", "expand", "language", "market", "observed", "subdiv", "years")
@cached_property
def _entity_code(self):
return getattr(self, "country", None) or getattr(self, "market", None)
@cached_property
def _normalized_subdiv(self):
return (
self.subdivisions_aliases.get(self.subdiv, self.subdiv)
.translate(str.maketrans({"-": "_", " ": "_"}))
.lower()
)
@property
def _sorted_categories(self):
return (
[self.default_category] + sorted(self.categories - {self.default_category})
if self.default_category in self.categories
else sorted(self.categories)
)
@classmethod
def get_subdivision_aliases(cls) -> dict[str, list]:
"""Get subdivision aliases.
Returns:
A dictionary mapping subdivision aliases to their official
[ISO 3166-2](https://en.wikipedia.org/wiki/ISO_3166-2) codes.
"""
subdivision_aliases: dict[str, list[str]] = {s: [] for s in cls.subdivisions}
for alias, subdivision in cls.subdivisions_aliases.items():
subdivision_aliases[subdivision].append(alias)
return subdivision_aliases
def _init_translation(self) -> None:
"""Initialize translation function based on language settings."""
supported_languages = set(self.supported_languages)
if self._entity_code is not None:
fallback = self.language not in supported_languages
languages = [self.language] if self.language in supported_languages else None
locale_directory = str(Path(__file__).with_name("locale"))
# Add entity native content translations.
entity_translation = translation(
self._entity_code,
fallback=fallback,
languages=languages,
localedir=locale_directory,
)
# Add a fallback if entity has parent translations.
if parent_entity := self.parent_entity:
entity_translation.add_fallback(
translation(
getattr(parent_entity, "country", None)
or getattr(parent_entity, "market", None), # type: ignore[arg-type]
fallback=fallback,
languages=languages,
localedir=locale_directory,
)
)
self.tr = entity_translation.gettext
else:
self.tr = gettext
def _is_leap_year(self) -> bool:
"""Returns True if the year is leap. Returns False otherwise."""
return isleap(self._year)
def _add_holiday(self, name: str, *args) -> date | None:
"""Add a holiday."""
if not args:
raise TypeError("Incorrect number of arguments.")
dt = args if len(args) > 1 else args[0]
dt = dt if isinstance(dt, date) else date(self._year, *dt)
if dt.year != self._year:
return None
self[dt] = self.tr(name)
return dt
def _add_multiday_holiday(
self, start_date: date, duration_days: int, *, name: str | None = None
) -> set[date]:
"""Add a multi-day holiday.
Args:
start_date:
First day of the holiday.
duration_days:
Number of additional days to add.
name:
Optional holiday name; inferred from `start_date` if omitted.
Returns:
A set of all added holiday dates.
Raises:
ValueError:
If the holiday name cannot be inferred from `start_date`.
"""
if (holiday_name := name or self.get(start_date)) is None:
raise ValueError(f"Cannot infer holiday name for date {start_date!r}.")
return {
d
for delta in range(1, duration_days + 1)
if (d := self._add_holiday(holiday_name, _timedelta(start_date, delta)))
}
def _add_special_holidays(self, mapping_names, *, observed=False):
"""Add special holidays."""
for mapping_name in mapping_names:
for data in _normalize_tuple(getattr(self, mapping_name, {}).get(self._year, ())):
if len(data) == 3: # Special holidays.
month, day, name = data
if isinstance(name, tuple): # Composite label (fmt, inner).
fmt, inner = name
translated_name = self.tr(fmt) % self.tr(inner)
else:
translated_name = (
self.tr(self.observed_label) % self.tr(name)
if observed
else self.tr(name)
)
self._add_holiday(translated_name, month, day)
else: # Substituted holidays.
to_month, to_day, from_month, from_day, *optional = data
from_date = date(optional[0] if optional else self._year, from_month, from_day)
self._add_holiday(
self.tr(self.substituted_label)
% from_date.strftime(self.tr(self.substituted_date_format)),
to_month,
to_day,
)
# when non-working day is transferred not from weekend, but from
# another transferred holiday (observed).
if self._is_weekend(from_date):
if from_date.year != self._year or from_date not in self:
self.weekend_workdays.add(from_date)
else:
if from_date.year == self._year and from_date in self:
self.pop(from_date)
def _check_weekday(self, weekday: int, *args) -> bool:
"""
Returns True if `weekday` equals to the date's week day.
Returns False otherwise.
"""
dt = args if len(args) > 1 else args[0]
dt = dt if isinstance(dt, date) else date(self._year, *dt)
return dt.weekday() == weekday
def _format_holiday_name(self, label: str, holiday_name: str) -> str:
return self.tr(label) % self.tr(holiday_name)
def _get_weekend(self, dt: date) -> set[int]:
return self.weekend
def _is_monday(self, *args) -> bool:
return self._check_weekday(MON, *args)
def _is_tuesday(self, *args) -> bool:
return self._check_weekday(TUE, *args)
def _is_wednesday(self, *args) -> bool:
return self._check_weekday(WED, *args)
def _is_thursday(self, *args) -> bool:
return self._check_weekday(THU, *args)
def _is_friday(self, *args) -> bool:
return self._check_weekday(FRI, *args)
def _is_saturday(self, *args) -> bool:
return self._check_weekday(SAT, *args)
def _is_sunday(self, *args) -> bool:
return self._check_weekday(SUN, *args)
def _is_weekday(self, *args) -> bool:
"""
Returns True if date's week day is not a weekend day.
Returns False otherwise.
"""
return not self._is_weekend(*args)
def _is_weekend(self, *args) -> bool:
"""
Returns True if date's week day is a weekend day.
Returns False otherwise.
"""
dt = args if len(args) > 1 else args[0]
dt = dt if isinstance(dt, date) else date(self._year, *dt)
return dt.weekday() in self._get_weekend(dt)
def _populate(self, year: int) -> None:
"""This is a private method that populates (generates and adds) holidays
for a given year. To keep things fast, it assumes that no holidays for
the year have already been populated. It is required to be called
internally by any country `populate()` method, while should not be called
directly from outside.
To add holidays to an object, use the [update()][holidays.holiday_base.HolidayBase.update]
method.
Args:
year: The year to populate with holidays.
>>> from holidays import country_holidays
>>> us_holidays = country_holidays('US', years=2020)
# to add new holidays to the object:
>>> us_holidays.update(country_holidays('US', years=2021))
"""
if year < self.start_year or year > self.end_year:
return None
self._year = year
self._populate_common_holidays()
self._populate_subdiv_holidays()
def _populate_common_holidays(self):
"""Populate entity common holidays."""
for category in self._sorted_categories:
if pch_method := getattr(self, f"_populate_{category.lower()}_holidays", None):
pch_method()
if self.has_special_holidays:
self._add_special_holidays(
f"special_{category}_holidays" for category in self._sorted_categories
)
def _populate_subdiv_holidays(self):
"""Populate entity subdivision holidays."""
if self.subdiv is None:
return None
for category in self._sorted_categories:
if asch_method := getattr(
self,
f"_populate_subdiv_{self._normalized_subdiv}_{category.lower()}_holidays",
None,
):
asch_method()
if self.has_special_holidays:
self._add_special_holidays(
f"special_{self._normalized_subdiv}_{category.lower()}_holidays"
for category in self._sorted_categories
)
def append(self, *args: dict[DateLike, str] | list[DateLike] | DateLike) -> None:
"""Alias for [update()][holidays.holiday_base.HolidayBase.update] to mimic list type.
Args:
args:
Holiday data to add. Can be:
* A dictionary mapping dates to holiday names.