index
int64 0
731k
| package
stringlengths 2
98
⌀ | name
stringlengths 1
76
| docstring
stringlengths 0
281k
⌀ | code
stringlengths 4
1.07M
⌀ | signature
stringlengths 2
42.8k
⌀ |
---|---|---|---|---|---|
39,744 | holidays.registry | get_country_codes | Get supported country codes.
:param include_aliases:
Whether to include entity aliases (e.g. UK for GB).
| @staticmethod
def get_country_codes(include_aliases: bool = True) -> Iterable[str]:
"""Get supported country codes.
:param include_aliases:
Whether to include entity aliases (e.g. UK for GB).
"""
return EntityLoader._get_entity_codes(COUNTRIES, 2, include_aliases)
| (include_aliases: bool = True) -> Iterable[str] |
39,745 | holidays.registry | get_entity | Return lazy-loaded entity. | def get_entity(self) -> Optional[HolidayBase]:
"""Return lazy-loaded entity."""
if self.entity is None:
self.entity = getattr(importlib.import_module(self.module_name), self.entity_name)
return self.entity
| (self) -> Optional[holidays.holiday_base.HolidayBase] |
39,746 | holidays.registry | get_financial_codes | Get supported financial codes.
:param include_aliases:
Whether to include entity aliases(e.g. TAR for ECB, XNYS for NYSE).
| @staticmethod
def get_financial_codes(include_aliases: bool = True) -> Iterable[str]:
"""Get supported financial codes.
:param include_aliases:
Whether to include entity aliases(e.g. TAR for ECB, XNYS for NYSE).
"""
return EntityLoader._get_entity_codes(FINANCIAL, (3, 4), include_aliases)
| (include_aliases: bool = True) -> Iterable[str] |
39,747 | holidays.registry | load | Load country or financial entities. | @staticmethod
def load(prefix: str, scope: Dict) -> None:
"""Load country or financial entities."""
entity_mapping = COUNTRIES if prefix == "countries" else FINANCIAL
for module, entities in entity_mapping.items():
scope.update(
{
entity: EntityLoader(f"holidays.{prefix}.{module}.{entity}")
for entity in entities
}
)
| (prefix: str, scope: Dict) -> NoneType |
39,748 | holidays.holiday_base | HolidayBase |
A dict-like object containing the holidays for a specific country (and
province or state if so initiated); inherits the dict class (so behaves
similarly to a dict). Dates without a key in the Holiday object are not
holidays.
The key of the object is the date of the holiday and the value is the name
of the holiday itself. When passing the date as a key, the date can be
expressed as one of the following formats:
* datetime.datetime type;
* datetime.date types;
* a float representing a Unix timestamp;
* or a string of any format (recognized by datetime.parse).
The key is always returned as a `datetime.date` object.
To maximize speed, the list of holidays is built as needed on the fly, one
calendar year at a time. When you instantiate the object, it is empty, but
the moment a key is accessed it will build that entire year's list of
holidays. To pre-populate holidays, instantiate the class with the years
argument:
us_holidays = holidays.US(years=2020)
It is generally instantiated using the :func:`country_holidays` function.
The key of the :class:`dict`-like :class:`HolidayBase` object is the
`date` of the holiday, and the value is the name of the holiday itself.
Dates where a key is not present are not public holidays (or, if
**observed** is False, days when a public holiday is observed).
When passing the `date` as a key, the `date` can be expressed in one of the
following types:
* :class:`datetime.date`,
* :class:`datetime.datetime`,
* a :class:`str` of any format recognized by :func:`dateutil.parser.parse`,
* or a :class:`float` or :class:`int` representing a POSIX timestamp.
The key is always returned as a :class:`datetime.date` object.
To maximize speed, the list of public holidays is built on the fly as
needed, one calendar year at a time. When the object is instantiated
without a **years** parameter, it is empty, but, unless **expand** is set
to False, as soon as a key is accessed the class will calculate that entire
year's list of holidays and set the keys with them.
If you need to list the holidays as opposed to querying individual dates,
instantiate the class with the **years** parameter.
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 :class:`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 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, 4), 'Independence Day')
(datetime.date(2020, 7, 3), 'Independence Day (observed)')
(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')
(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:
* a :class:`dict` with date/name key/value pairs (e.g.
``{'2010-07-10': 'My birthday!'}``),
* a list of dates (as a :class:`datetime.date`, :class:`datetime.datetime`,
:class:`str`, :class:`int`, or :class:`float`); ``'Holiday'`` will be
used as a description,
* or a single date item (of one of the types above); ``'Holiday'`` will be
used as a description:
>>> 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
:attr:`special_public_holidays`:
.. code-block:: python
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
:class:`HolidayBase` class and define your own :meth:`_populate` method.
See documentation for examples.
| class HolidayBase(Dict[date, str]):
"""
A dict-like object containing the holidays for a specific country (and
province or state if so initiated); inherits the dict class (so behaves
similarly to a dict). Dates without a key in the Holiday object are not
holidays.
The key of the object is the date of the holiday and the value is the name
of the holiday itself. When passing the date as a key, the date can be
expressed as one of the following formats:
* datetime.datetime type;
* datetime.date types;
* a float representing a Unix timestamp;
* or a string of any format (recognized by datetime.parse).
The key is always returned as a `datetime.date` object.
To maximize speed, the list of holidays is built as needed on the fly, one
calendar year at a time. When you instantiate the object, it is empty, but
the moment a key is accessed it will build that entire year's list of
holidays. To pre-populate holidays, instantiate the class with the years
argument:
us_holidays = holidays.US(years=2020)
It is generally instantiated using the :func:`country_holidays` function.
The key of the :class:`dict`-like :class:`HolidayBase` object is the
`date` of the holiday, and the value is the name of the holiday itself.
Dates where a key is not present are not public holidays (or, if
**observed** is False, days when a public holiday is observed).
When passing the `date` as a key, the `date` can be expressed in one of the
following types:
* :class:`datetime.date`,
* :class:`datetime.datetime`,
* a :class:`str` of any format recognized by :func:`dateutil.parser.parse`,
* or a :class:`float` or :class:`int` representing a POSIX timestamp.
The key is always returned as a :class:`datetime.date` object.
To maximize speed, the list of public holidays is built on the fly as
needed, one calendar year at a time. When the object is instantiated
without a **years** parameter, it is empty, but, unless **expand** is set
to False, as soon as a key is accessed the class will calculate that entire
year's list of holidays and set the keys with them.
If you need to list the holidays as opposed to querying individual dates,
instantiate the class with the **years** parameter.
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 :class:`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 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, 4), 'Independence Day')
(datetime.date(2020, 7, 3), 'Independence Day (observed)')
(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')
(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:
* a :class:`dict` with date/name key/value pairs (e.g.
``{'2010-07-10': 'My birthday!'}``),
* a list of dates (as a :class:`datetime.date`, :class:`datetime.datetime`,
:class:`str`, :class:`int`, or :class:`float`); ``'Holiday'`` will be
used as a description,
* or a single date item (of one of the types above); ``'Holiday'`` will be
used as a description:
>>> 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
:attr:`special_public_holidays`:
.. code-block:: python
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
:class:`HolidayBase` class and define your own :meth:`_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: Optional[str] = None
"""The subdiv requested as ISO 3166-2 code or one of the aliases."""
special_holidays: Dict[int, Union[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] = set()
"""Working days moved to weekends."""
default_category: str = PUBLIC
"""The entity category used by default."""
default_language: Optional[str] = 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."""
def __init__(
self,
years: Optional[YearArg] = None,
expand: bool = True,
observed: bool = True,
subdiv: Optional[str] = None,
prov: Optional[str] = None, # Deprecated.
state: Optional[str] = None, # Deprecated.
language: Optional[str] = None,
categories: Optional[CategoryArg] = None,
) -> None:
"""
:param years:
The year(s) to pre-calculate public holidays for at instantiation.
:param expand:
Whether the entire year is calculated when one date from that year
is requested.
:param 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.
:param subdiv:
The subdivision (e.g. state or province) as a ISO 3166-2 code
or its alias; not implemented for all countries (see documentation).
:param prov:
*deprecated* use subdiv instead.
:param state:
*deprecated* use subdiv instead.
:param language:
The language which the returned holiday names will be translated
into. It must be an ISO 639-1 (2-letter) language code. If the
language translation is not supported the original holiday names
will be used.
:param categories:
Requested holiday categories.
:return:
A :class:`HolidayBase` object matching the **country**.
"""
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)
subdivisions_aliases = tuple(sorted(self.subdivisions_aliases))
# Unsupported subdivisions.
if not isinstance(self, HolidaySum) and subdiv not in (
self.subdivisions + subdivisions_aliases + self._deprecated_subdivisions
):
raise NotImplementedError(
f"Entity `{self._entity_code}` does not have subdivision {subdiv}"
)
# Deprecated arguments.
if prov_state := prov or state:
warnings.warn(
"Arguments prov and state are deprecated, use "
f"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(subdivisions_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.lower() if language else None
self.observed = observed
self.subdiv = subdiv
self.weekend_workdays = set()
supported_languages = set(self.supported_languages)
self.tr = (
translation(
self._entity_code,
fallback=language not in supported_languages,
languages=[language] if language in supported_languages else None,
localedir=str(Path(__file__).with_name("locale")),
).gettext
if self._entity_code is not None
else gettext
)
self.years = _normalize_arguments(int, years)
# Populate holidays.
for year in self.years:
self._populate(year)
def __add__(self, other: Union[int, "HolidayBase", "HolidaySum"]) -> "HolidayBase":
"""Add another dictionary of public holidays creating a
:class:`HolidaySum` object.
:param other:
The dictionary of public holiday to be added.
:return:
A :class:`HolidaySum` object unless the other object cannot be
added, then :class:`self`.
"""
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:
"""Return true if date is in self, false otherwise. Accepts a date in
the following types:
* :class:`datetime.date`,
* :class:`datetime.datetime`,
* a :class:`str` of any format recognized by
:func:`dateutil.parser.parse`,
* or a :class:`float` or :class:`int` representing a POSIX timestamp.
"""
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,
self._easter_sunday
+ timedelta(days=+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,
_get_nth_weekday_of_month(
-1 if number == "last" else int(number[0]),
WEEKDAYS[weekday],
MONTHS[month],
self._year,
)
+ timedelta(days=+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, timedelta):
step = key.step.days
elif isinstance(key.step, int):
step = key.step
else:
raise TypeError(f"Cannot convert type '{type(key.step)}' to int.")
if step == 0:
raise ValueError("Step value must not be zero.")
date_diff = stop - start
if date_diff.days < 0 <= step or date_diff.days >= 0 > step:
step *= -1
days_in_range = []
for delta_days in range(0, date_diff.days, step):
day = start + timedelta(days=delta_days)
if day in self:
days_in_range.append(day)
return days_in_range
return dict.__getitem__(self, self.__keytransform__(key))
def __keytransform__(self, key: DateLike) -> date:
"""Transforms the date from one of the following types:
* :class:`datetime.date`,
* :class:`datetime.datetime`,
* a :class:`str` of any format recognized by
:func:`dateutil.parser.parse`,
* or a :class:`float` or :class:`int` representing a POSIX timestamp
to :class:`datetime.date`, which is how it's stored by the class."""
# 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):
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) -> Union[str, Tuple[Any, ...]]:
return super().__reduce__()
def __repr__(self) -> str:
if self:
return super().__repr__()
parts = []
if hasattr(self, "market"):
parts.append(f"holidays.financial_holidays({self.market!r}")
parts.append(")")
elif hasattr(self, "country"):
parts.append(f"holidays.country_holidays({self.country!r}")
if self.subdiv:
parts.append(f", subdiv={self.subdiv!r}")
parts.append(")")
else:
parts.append("holidays.HolidayBase()")
return "".join(parts)
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.add(value)
value = HOLIDAY_NAME_DELIMITER.join(sorted(holiday_names))
dict.__setitem__(self, self.__keytransform__(key), value)
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", 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."""
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 _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) -> Optional[date]:
"""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_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
self._add_holiday(
self.tr(self.observed_label) % self.tr(name)
if observed
else self.tr(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,
)
self.weekend_workdays.add(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 _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_weekend(self, *args):
"""
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.weekend
def _populate(self, year: int) -> None:
"""This is a private class 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() method.
:param 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))
"""
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: Union[Dict[DateLike, str], List[DateLike], DateLike]) -> None:
"""Alias for :meth:`update` to mimic list type."""
return self.update(*args)
def copy(self):
"""Return a copy of the object."""
return copy.copy(self)
def get(self, key: DateLike, default: Union[str, Any] = None) -> Union[str, Any]:
"""Return the holiday name for a date if date is a holiday, else
default. If default is not given, it defaults to None, so that this
method never raises a KeyError. If more than one holiday is present,
they are separated by a comma.
:param key:
The date expressed in one of the following types:
* :class:`datetime.date`,
* :class:`datetime.datetime`,
* a :class:`str` of any format recognized by
:func:`dateutil.parser.parse`,
* or a :class:`float` or :class:`int` representing a POSIX
timestamp.
:param default:
The default value to return if no value is found.
"""
return dict.get(self, self.__keytransform__(key), default)
def get_list(self, key: DateLike) -> List[str]:
"""Return a list of all holiday names for a date if date is a holiday,
else empty string.
:param key:
The date expressed in one of the following types:
* :class:`datetime.date`,
* :class:`datetime.datetime`,
* a :class:`str` of any format recognized by
:func:`dateutil.parser.parse`,
* or a :class:`float` or :class:`int` representing a POSIX
timestamp.
"""
return [name for name in self.get(key, "").split(HOLIDAY_NAME_DELIMITER) if name]
def get_named(
self, holiday_name: str, lookup="icontains", split_multiple_names=True
) -> List[date]:
"""Return a list of all holiday dates matching the provided holiday
name. The match will be made case insensitively and partial matches
will be included by default.
:param holiday_name:
The holiday's name to try to match.
:param lookup:
The holiday name lookup type:
contains - case sensitive contains match;
exact - case sensitive exact match;
startswith - case sensitive starts with match;
icontains - case insensitive contains match;
iexact - case insensitive exact match;
istartswith - case insensitive starts with match;
:param split_multiple_names:
Either use the exact name for each date or split it by holiday
name delimiter.
:return:
A list of all holiday dates matching the provided holiday name.
"""
holiday_name_dates = (
((k, name) for k, v in self.items() for name in v.split(HOLIDAY_NAME_DELIMITER))
if split_multiple_names
else ((k, v) for k, v in self.items())
)
if lookup == "icontains":
holiday_name_lower = holiday_name.lower()
return [dt for dt, name in holiday_name_dates if holiday_name_lower in name.lower()]
elif lookup == "exact":
return [dt for dt, name in holiday_name_dates if holiday_name == name]
elif lookup == "contains":
return [dt for dt, name in holiday_name_dates if holiday_name in name]
elif lookup == "startswith":
return [
dt for dt, name in holiday_name_dates if holiday_name == name[: len(holiday_name)]
]
elif lookup == "iexact":
holiday_name_lower = holiday_name.lower()
return [dt for dt, name in holiday_name_dates if holiday_name_lower == name.lower()]
elif lookup == "istartswith":
holiday_name_lower = holiday_name.lower()
return [
dt
for dt, name in holiday_name_dates
if holiday_name_lower == name[: len(holiday_name)].lower()
]
raise AttributeError(f"Unknown lookup type: {lookup}")
def get_nth_workday(self, key: DateLike, n: int) -> date:
"""Return n-th working day from provided date (if n is positive)
or n-th working day before provided date (if n is negative).
"""
direction = +1 if n > 0 else -1
dt = self.__keytransform__(key)
for _ in range(abs(n)):
dt += timedelta(days=direction)
while not self.is_workday(dt):
dt += timedelta(days=direction)
return dt
def get_workdays_number(self, key1: DateLike, key2: DateLike) -> int:
"""Return the number of working days between two dates (not including the start date)."""
dt1 = self.__keytransform__(key1)
dt2 = self.__keytransform__(key2)
if dt1 == dt2:
return 0
if dt1 > dt2:
dt1, dt2 = dt2, dt1
return sum(
self.is_workday(dt1 + timedelta(days=n)) for n in range(1, (dt2 - dt1).days + 1)
)
def is_workday(self, key: DateLike) -> bool:
"""Return True if date is a working day (not a holiday or a weekend)."""
dt = self.__keytransform__(key)
return dt in self.weekend_workdays if self._is_weekend(dt) else dt not in self
def pop(self, key: DateLike, default: Union[str, Any] = None) -> Union[str, Any]:
"""If date is a holiday, remove it and return its date, else return
default.
:param key:
The date expressed in one of the following types:
* :class:`datetime.date`,
* :class:`datetime.datetime`,
* a :class:`str` of any format recognized by
:func:`dateutil.parser.parse`,
* or a :class:`float` or :class:`int` representing a POSIX
timestamp.
:param default:
The default value to return if no match is found.
:return:
The date removed.
:raise:
KeyError if date is not a holiday and default is not given.
"""
if default is None:
return dict.pop(self, self.__keytransform__(key))
return dict.pop(self, self.__keytransform__(key), default)
def pop_named(self, name: str) -> List[date]:
"""Remove (no longer treat at as holiday) all dates matching the
provided holiday name. The match will be made case insensitively and
partial matches will be removed.
:param name:
The holiday's name to try to match.
:param default:
The default value to return if no match is found.
:return:
A list of dates removed.
:raise:
KeyError if date is not a holiday and default is not given.
"""
use_exact_name = HOLIDAY_NAME_DELIMITER in name
dts = self.get_named(name, split_multiple_names=not use_exact_name)
if len(dts) == 0:
raise KeyError(name)
popped = []
for dt in dts:
holiday_names = self[dt].split(HOLIDAY_NAME_DELIMITER)
self.pop(dt)
popped.append(dt)
# Keep the rest of holidays falling on the same date.
if not use_exact_name:
name_lower = name.lower()
holiday_names = [
holiday_name
for holiday_name in holiday_names
if name_lower not in holiday_name.lower()
]
if len(holiday_names) > 0:
self[dt] = HOLIDAY_NAME_DELIMITER.join(holiday_names)
return popped
def update( # type: ignore[override]
self, *args: Union[Dict[DateLike, str], List[DateLike], DateLike]
) -> None:
# TODO: fix arguments; should not be *args (cannot properly Type hint)
"""Update the object, overwriting existing dates.
:param:
Either another dictionary object where keys are dates and values
are holiday names, or a single date (or a list of dates) for which
the value will be set to "Holiday".
Dates can be expressed in one or more of the following types:
* :class:`datetime.date`,
* :class:`datetime.datetime`,
* a :class:`str` of any format recognized by
:func:`dateutil.parser.parse`,
* or a :class:`float` or :class:`int` representing a POSIX
timestamp.
"""
for arg in args:
if isinstance(arg, dict):
for key, value in arg.items():
self[key] = value
elif isinstance(arg, list):
for item in arg:
self[item] = "Holiday"
else:
self[arg] = "Holiday"
| (years: Set[int] = None, expand: bool = True, observed: bool = True, subdiv: Optional[str] = None, prov: Optional[str] = None, state: Optional[str] = None, language: Optional[str] = None, categories: Set[str] = None) -> None |
39,749 | holidays.holiday_base | __add__ | Add another dictionary of public holidays creating a
:class:`HolidaySum` object.
:param other:
The dictionary of public holiday to be added.
:return:
A :class:`HolidaySum` object unless the other object cannot be
added, then :class:`self`.
| def __add__(self, other: Union[int, "HolidayBase", "HolidaySum"]) -> "HolidayBase":
"""Add another dictionary of public holidays creating a
:class:`HolidaySum` object.
:param other:
The dictionary of public holiday to be added.
:return:
A :class:`HolidaySum` object unless the other object cannot be
added, then :class:`self`.
"""
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)
| (self, other: Union[int, holidays.holiday_base.HolidayBase, holidays.holiday_base.HolidaySum]) -> holidays.holiday_base.HolidayBase |
39,750 | holidays.holiday_base | __bool__ | null | def __bool__(self) -> bool:
return len(self) > 0
| (self) -> bool |
39,751 | holidays.holiday_base | __contains__ | Return true if date is in self, false otherwise. Accepts a date in
the following types:
* :class:`datetime.date`,
* :class:`datetime.datetime`,
* a :class:`str` of any format recognized by
:func:`dateutil.parser.parse`,
* or a :class:`float` or :class:`int` representing a POSIX timestamp.
| def __contains__(self, key: object) -> bool:
"""Return true if date is in self, false otherwise. Accepts a date in
the following types:
* :class:`datetime.date`,
* :class:`datetime.datetime`,
* a :class:`str` of any format recognized by
:func:`dateutil.parser.parse`,
* or a :class:`float` or :class:`int` representing a POSIX timestamp.
"""
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))
| (self, key: object) -> bool |
39,752 | holidays.holiday_base | __eq__ | null | 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)
| (self, other: object) -> bool |
39,753 | holidays.holiday_base | __getattr__ | null | 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,
self._easter_sunday
+ timedelta(days=+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,
_get_nth_weekday_of_month(
-1 if number == "last" else int(number[0]),
WEEKDAYS[weekday],
MONTHS[month],
self._year,
)
+ timedelta(days=+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.
| (self, name) |
39,754 | holidays.holiday_base | __getitem__ | null | 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, timedelta):
step = key.step.days
elif isinstance(key.step, int):
step = key.step
else:
raise TypeError(f"Cannot convert type '{type(key.step)}' to int.")
if step == 0:
raise ValueError("Step value must not be zero.")
date_diff = stop - start
if date_diff.days < 0 <= step or date_diff.days >= 0 > step:
step *= -1
days_in_range = []
for delta_days in range(0, date_diff.days, step):
day = start + timedelta(days=delta_days)
if day in self:
days_in_range.append(day)
return days_in_range
return dict.__getitem__(self, self.__keytransform__(key))
| (self, key: Union[datetime.date, datetime.datetime, str, float, int]) -> Any |
39,755 | holidays.holiday_base | __init__ |
:param years:
The year(s) to pre-calculate public holidays for at instantiation.
:param expand:
Whether the entire year is calculated when one date from that year
is requested.
:param 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.
:param subdiv:
The subdivision (e.g. state or province) as a ISO 3166-2 code
or its alias; not implemented for all countries (see documentation).
:param prov:
*deprecated* use subdiv instead.
:param state:
*deprecated* use subdiv instead.
:param language:
The language which the returned holiday names will be translated
into. It must be an ISO 639-1 (2-letter) language code. If the
language translation is not supported the original holiday names
will be used.
:param categories:
Requested holiday categories.
:return:
A :class:`HolidayBase` object matching the **country**.
| def __init__(
self,
years: Optional[YearArg] = None,
expand: bool = True,
observed: bool = True,
subdiv: Optional[str] = None,
prov: Optional[str] = None, # Deprecated.
state: Optional[str] = None, # Deprecated.
language: Optional[str] = None,
categories: Optional[CategoryArg] = None,
) -> None:
"""
:param years:
The year(s) to pre-calculate public holidays for at instantiation.
:param expand:
Whether the entire year is calculated when one date from that year
is requested.
:param 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.
:param subdiv:
The subdivision (e.g. state or province) as a ISO 3166-2 code
or its alias; not implemented for all countries (see documentation).
:param prov:
*deprecated* use subdiv instead.
:param state:
*deprecated* use subdiv instead.
:param language:
The language which the returned holiday names will be translated
into. It must be an ISO 639-1 (2-letter) language code. If the
language translation is not supported the original holiday names
will be used.
:param categories:
Requested holiday categories.
:return:
A :class:`HolidayBase` object matching the **country**.
"""
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)
subdivisions_aliases = tuple(sorted(self.subdivisions_aliases))
# Unsupported subdivisions.
if not isinstance(self, HolidaySum) and subdiv not in (
self.subdivisions + subdivisions_aliases + self._deprecated_subdivisions
):
raise NotImplementedError(
f"Entity `{self._entity_code}` does not have subdivision {subdiv}"
)
# Deprecated arguments.
if prov_state := prov or state:
warnings.warn(
"Arguments prov and state are deprecated, use "
f"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(subdivisions_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.lower() if language else None
self.observed = observed
self.subdiv = subdiv
self.weekend_workdays = set()
supported_languages = set(self.supported_languages)
self.tr = (
translation(
self._entity_code,
fallback=language not in supported_languages,
languages=[language] if language in supported_languages else None,
localedir=str(Path(__file__).with_name("locale")),
).gettext
if self._entity_code is not None
else gettext
)
self.years = _normalize_arguments(int, years)
# Populate holidays.
for year in self.years:
self._populate(year)
| (self, years: Union[int, Iterable[int], NoneType] = None, expand: bool = True, observed: bool = True, subdiv: Optional[str] = None, prov: Optional[str] = None, state: Optional[str] = None, language: Optional[str] = None, categories: Union[str, Iterable[str], NoneType] = None) -> NoneType |
39,756 | holidays.holiday_base | __keytransform__ | Transforms the date from one of the following types:
* :class:`datetime.date`,
* :class:`datetime.datetime`,
* a :class:`str` of any format recognized by
:func:`dateutil.parser.parse`,
* or a :class:`float` or :class:`int` representing a POSIX timestamp
to :class:`datetime.date`, which is how it's stored by the class. | def __keytransform__(self, key: DateLike) -> date:
"""Transforms the date from one of the following types:
* :class:`datetime.date`,
* :class:`datetime.datetime`,
* a :class:`str` of any format recognized by
:func:`dateutil.parser.parse`,
* or a :class:`float` or :class:`int` representing a POSIX timestamp
to :class:`datetime.date`, which is how it's stored by the class."""
# 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):
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
| (self, key: Union[datetime.date, datetime.datetime, str, float, int]) -> datetime.date |
39,757 | holidays.holiday_base | __ne__ | null | 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)
| (self, other: object) -> bool |
39,758 | holidays.holiday_base | __radd__ | null | def __radd__(self, other: Any) -> "HolidayBase":
return self.__add__(other)
| (self, other: Any) -> holidays.holiday_base.HolidayBase |
39,759 | holidays.holiday_base | __reduce__ | null | def __reduce__(self) -> Union[str, Tuple[Any, ...]]:
return super().__reduce__()
| (self) -> Union[str, Tuple[Any, ...]] |
39,760 | holidays.holiday_base | __repr__ | null | def __repr__(self) -> str:
if self:
return super().__repr__()
parts = []
if hasattr(self, "market"):
parts.append(f"holidays.financial_holidays({self.market!r}")
parts.append(")")
elif hasattr(self, "country"):
parts.append(f"holidays.country_holidays({self.country!r}")
if self.subdiv:
parts.append(f", subdiv={self.subdiv!r}")
parts.append(")")
else:
parts.append("holidays.HolidayBase()")
return "".join(parts)
| (self) -> str |
39,761 | holidays.holiday_base | __setattr__ | null | 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)
| (self, key: str, value: Any) -> NoneType |
39,762 | holidays.holiday_base | __setitem__ | null | 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.add(value)
value = HOLIDAY_NAME_DELIMITER.join(sorted(holiday_names))
dict.__setitem__(self, self.__keytransform__(key), value)
| (self, key: Union[datetime.date, datetime.datetime, str, float, int], value: str) -> NoneType |
39,763 | holidays.holiday_base | __str__ | null | 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)}}}"
| (self) -> str |
39,764 | holidays.holiday_base | _add_holiday | Add a holiday. | def _add_holiday(self, name: str, *args) -> Optional[date]:
"""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
| (self, name: str, *args) -> Optional[datetime.date] |
39,765 | holidays.holiday_base | _add_special_holidays | Add special holidays. | 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
self._add_holiday(
self.tr(self.observed_label) % self.tr(name)
if observed
else self.tr(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,
)
self.weekend_workdays.add(from_date)
| (self, mapping_names, observed=False) |
39,766 | holidays.holiday_base | _check_weekday |
Returns True if `weekday` equals to the date's week day.
Returns False otherwise.
| 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
| (self, weekday: int, *args) -> bool |
39,767 | holidays.holiday_base | _is_friday | null | def _is_friday(self, *args) -> bool:
return self._check_weekday(FRI, *args)
| (self, *args) -> bool |
39,768 | holidays.holiday_base | _is_leap_year |
Returns True if the year is leap. Returns False otherwise.
| def _is_leap_year(self) -> bool:
"""
Returns True if the year is leap. Returns False otherwise.
"""
return isleap(self._year)
| (self) -> bool |
39,769 | holidays.holiday_base | _is_monday | null | def _is_monday(self, *args) -> bool:
return self._check_weekday(MON, *args)
| (self, *args) -> bool |
39,770 | holidays.holiday_base | _is_saturday | null | def _is_saturday(self, *args) -> bool:
return self._check_weekday(SAT, *args)
| (self, *args) -> bool |
39,771 | holidays.holiday_base | _is_sunday | null | def _is_sunday(self, *args) -> bool:
return self._check_weekday(SUN, *args)
| (self, *args) -> bool |
39,772 | holidays.holiday_base | _is_thursday | null | def _is_thursday(self, *args) -> bool:
return self._check_weekday(THU, *args)
| (self, *args) -> bool |
39,773 | holidays.holiday_base | _is_tuesday | null | def _is_tuesday(self, *args) -> bool:
return self._check_weekday(TUE, *args)
| (self, *args) -> bool |
39,774 | holidays.holiday_base | _is_wednesday | null | def _is_wednesday(self, *args) -> bool:
return self._check_weekday(WED, *args)
| (self, *args) -> bool |
39,775 | holidays.holiday_base | _is_weekend |
Returns True if date's week day is a weekend day.
Returns False otherwise.
| def _is_weekend(self, *args):
"""
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.weekend
| (self, *args) |
39,776 | holidays.holiday_base | _populate | This is a private class 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() method.
:param 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))
| def _populate(self, year: int) -> None:
"""This is a private class 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() method.
:param 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))
"""
self._year = year
self._populate_common_holidays()
self._populate_subdiv_holidays()
| (self, year: int) -> NoneType |
39,777 | holidays.holiday_base | _populate_common_holidays | Populate entity common 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
)
| (self) |
39,778 | holidays.holiday_base | _populate_subdiv_holidays | Populate entity subdivision holidays. | 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
)
| (self) |
39,779 | holidays.holiday_base | append | Alias for :meth:`update` to mimic list type. | def append(self, *args: Union[Dict[DateLike, str], List[DateLike], DateLike]) -> None:
"""Alias for :meth:`update` to mimic list type."""
return self.update(*args)
| (self, *args: Union[Dict[Union[datetime.date, datetime.datetime, str, float, int], str], List[Union[datetime.date, datetime.datetime, str, float, int]], datetime.date, datetime.datetime, str, float, int]) -> NoneType |
39,780 | holidays.holiday_base | copy | Return a copy of the object. | def copy(self):
"""Return a copy of the object."""
return copy.copy(self)
| (self) |
39,781 | holidays.holiday_base | get | Return the holiday name for a date if date is a holiday, else
default. If default is not given, it defaults to None, so that this
method never raises a KeyError. If more than one holiday is present,
they are separated by a comma.
:param key:
The date expressed in one of the following types:
* :class:`datetime.date`,
* :class:`datetime.datetime`,
* a :class:`str` of any format recognized by
:func:`dateutil.parser.parse`,
* or a :class:`float` or :class:`int` representing a POSIX
timestamp.
:param default:
The default value to return if no value is found.
| def get(self, key: DateLike, default: Union[str, Any] = None) -> Union[str, Any]:
"""Return the holiday name for a date if date is a holiday, else
default. If default is not given, it defaults to None, so that this
method never raises a KeyError. If more than one holiday is present,
they are separated by a comma.
:param key:
The date expressed in one of the following types:
* :class:`datetime.date`,
* :class:`datetime.datetime`,
* a :class:`str` of any format recognized by
:func:`dateutil.parser.parse`,
* or a :class:`float` or :class:`int` representing a POSIX
timestamp.
:param default:
The default value to return if no value is found.
"""
return dict.get(self, self.__keytransform__(key), default)
| (self, key: Union[datetime.date, datetime.datetime, str, float, int], default: Union[str, Any, NoneType] = None) -> Union[str, Any] |
39,782 | holidays.holiday_base | get_list | Return a list of all holiday names for a date if date is a holiday,
else empty string.
:param key:
The date expressed in one of the following types:
* :class:`datetime.date`,
* :class:`datetime.datetime`,
* a :class:`str` of any format recognized by
:func:`dateutil.parser.parse`,
* or a :class:`float` or :class:`int` representing a POSIX
timestamp.
| def get_list(self, key: DateLike) -> List[str]:
"""Return a list of all holiday names for a date if date is a holiday,
else empty string.
:param key:
The date expressed in one of the following types:
* :class:`datetime.date`,
* :class:`datetime.datetime`,
* a :class:`str` of any format recognized by
:func:`dateutil.parser.parse`,
* or a :class:`float` or :class:`int` representing a POSIX
timestamp.
"""
return [name for name in self.get(key, "").split(HOLIDAY_NAME_DELIMITER) if name]
| (self, key: Union[datetime.date, datetime.datetime, str, float, int]) -> List[str] |
39,783 | holidays.holiday_base | get_named | Return a list of all holiday dates matching the provided holiday
name. The match will be made case insensitively and partial matches
will be included by default.
:param holiday_name:
The holiday's name to try to match.
:param lookup:
The holiday name lookup type:
contains - case sensitive contains match;
exact - case sensitive exact match;
startswith - case sensitive starts with match;
icontains - case insensitive contains match;
iexact - case insensitive exact match;
istartswith - case insensitive starts with match;
:param split_multiple_names:
Either use the exact name for each date or split it by holiday
name delimiter.
:return:
A list of all holiday dates matching the provided holiday name.
| def get_named(
self, holiday_name: str, lookup="icontains", split_multiple_names=True
) -> List[date]:
"""Return a list of all holiday dates matching the provided holiday
name. The match will be made case insensitively and partial matches
will be included by default.
:param holiday_name:
The holiday's name to try to match.
:param lookup:
The holiday name lookup type:
contains - case sensitive contains match;
exact - case sensitive exact match;
startswith - case sensitive starts with match;
icontains - case insensitive contains match;
iexact - case insensitive exact match;
istartswith - case insensitive starts with match;
:param split_multiple_names:
Either use the exact name for each date or split it by holiday
name delimiter.
:return:
A list of all holiday dates matching the provided holiday name.
"""
holiday_name_dates = (
((k, name) for k, v in self.items() for name in v.split(HOLIDAY_NAME_DELIMITER))
if split_multiple_names
else ((k, v) for k, v in self.items())
)
if lookup == "icontains":
holiday_name_lower = holiday_name.lower()
return [dt for dt, name in holiday_name_dates if holiday_name_lower in name.lower()]
elif lookup == "exact":
return [dt for dt, name in holiday_name_dates if holiday_name == name]
elif lookup == "contains":
return [dt for dt, name in holiday_name_dates if holiday_name in name]
elif lookup == "startswith":
return [
dt for dt, name in holiday_name_dates if holiday_name == name[: len(holiday_name)]
]
elif lookup == "iexact":
holiday_name_lower = holiday_name.lower()
return [dt for dt, name in holiday_name_dates if holiday_name_lower == name.lower()]
elif lookup == "istartswith":
holiday_name_lower = holiday_name.lower()
return [
dt
for dt, name in holiday_name_dates
if holiday_name_lower == name[: len(holiday_name)].lower()
]
raise AttributeError(f"Unknown lookup type: {lookup}")
| (self, holiday_name: str, lookup='icontains', split_multiple_names=True) -> List[datetime.date] |
39,784 | holidays.holiday_base | get_nth_workday | Return n-th working day from provided date (if n is positive)
or n-th working day before provided date (if n is negative).
| def get_nth_workday(self, key: DateLike, n: int) -> date:
"""Return n-th working day from provided date (if n is positive)
or n-th working day before provided date (if n is negative).
"""
direction = +1 if n > 0 else -1
dt = self.__keytransform__(key)
for _ in range(abs(n)):
dt += timedelta(days=direction)
while not self.is_workday(dt):
dt += timedelta(days=direction)
return dt
| (self, key: Union[datetime.date, datetime.datetime, str, float, int], n: int) -> datetime.date |
39,785 | holidays.holiday_base | get_workdays_number | Return the number of working days between two dates (not including the start date). | def get_workdays_number(self, key1: DateLike, key2: DateLike) -> int:
"""Return the number of working days between two dates (not including the start date)."""
dt1 = self.__keytransform__(key1)
dt2 = self.__keytransform__(key2)
if dt1 == dt2:
return 0
if dt1 > dt2:
dt1, dt2 = dt2, dt1
return sum(
self.is_workday(dt1 + timedelta(days=n)) for n in range(1, (dt2 - dt1).days + 1)
)
| (self, key1: Union[datetime.date, datetime.datetime, str, float, int], key2: Union[datetime.date, datetime.datetime, str, float, int]) -> int |
39,786 | holidays.holiday_base | is_workday | Return True if date is a working day (not a holiday or a weekend). | def is_workday(self, key: DateLike) -> bool:
"""Return True if date is a working day (not a holiday or a weekend)."""
dt = self.__keytransform__(key)
return dt in self.weekend_workdays if self._is_weekend(dt) else dt not in self
| (self, key: Union[datetime.date, datetime.datetime, str, float, int]) -> bool |
39,787 | holidays.holiday_base | pop | If date is a holiday, remove it and return its date, else return
default.
:param key:
The date expressed in one of the following types:
* :class:`datetime.date`,
* :class:`datetime.datetime`,
* a :class:`str` of any format recognized by
:func:`dateutil.parser.parse`,
* or a :class:`float` or :class:`int` representing a POSIX
timestamp.
:param default:
The default value to return if no match is found.
:return:
The date removed.
:raise:
KeyError if date is not a holiday and default is not given.
| def pop(self, key: DateLike, default: Union[str, Any] = None) -> Union[str, Any]:
"""If date is a holiday, remove it and return its date, else return
default.
:param key:
The date expressed in one of the following types:
* :class:`datetime.date`,
* :class:`datetime.datetime`,
* a :class:`str` of any format recognized by
:func:`dateutil.parser.parse`,
* or a :class:`float` or :class:`int` representing a POSIX
timestamp.
:param default:
The default value to return if no match is found.
:return:
The date removed.
:raise:
KeyError if date is not a holiday and default is not given.
"""
if default is None:
return dict.pop(self, self.__keytransform__(key))
return dict.pop(self, self.__keytransform__(key), default)
| (self, key: Union[datetime.date, datetime.datetime, str, float, int], default: Union[str, Any, NoneType] = None) -> Union[str, Any] |
39,788 | holidays.holiday_base | pop_named | Remove (no longer treat at as holiday) all dates matching the
provided holiday name. The match will be made case insensitively and
partial matches will be removed.
:param name:
The holiday's name to try to match.
:param default:
The default value to return if no match is found.
:return:
A list of dates removed.
:raise:
KeyError if date is not a holiday and default is not given.
| def pop_named(self, name: str) -> List[date]:
"""Remove (no longer treat at as holiday) all dates matching the
provided holiday name. The match will be made case insensitively and
partial matches will be removed.
:param name:
The holiday's name to try to match.
:param default:
The default value to return if no match is found.
:return:
A list of dates removed.
:raise:
KeyError if date is not a holiday and default is not given.
"""
use_exact_name = HOLIDAY_NAME_DELIMITER in name
dts = self.get_named(name, split_multiple_names=not use_exact_name)
if len(dts) == 0:
raise KeyError(name)
popped = []
for dt in dts:
holiday_names = self[dt].split(HOLIDAY_NAME_DELIMITER)
self.pop(dt)
popped.append(dt)
# Keep the rest of holidays falling on the same date.
if not use_exact_name:
name_lower = name.lower()
holiday_names = [
holiday_name
for holiday_name in holiday_names
if name_lower not in holiday_name.lower()
]
if len(holiday_names) > 0:
self[dt] = HOLIDAY_NAME_DELIMITER.join(holiday_names)
return popped
| (self, name: str) -> List[datetime.date] |
39,789 | holidays.holiday_base | update | Update the object, overwriting existing dates.
:param:
Either another dictionary object where keys are dates and values
are holiday names, or a single date (or a list of dates) for which
the value will be set to "Holiday".
Dates can be expressed in one or more of the following types:
* :class:`datetime.date`,
* :class:`datetime.datetime`,
* a :class:`str` of any format recognized by
:func:`dateutil.parser.parse`,
* or a :class:`float` or :class:`int` representing a POSIX
timestamp.
| def update( # type: ignore[override]
self, *args: Union[Dict[DateLike, str], List[DateLike], DateLike]
) -> None:
# TODO: fix arguments; should not be *args (cannot properly Type hint)
"""Update the object, overwriting existing dates.
:param:
Either another dictionary object where keys are dates and values
are holiday names, or a single date (or a list of dates) for which
the value will be set to "Holiday".
Dates can be expressed in one or more of the following types:
* :class:`datetime.date`,
* :class:`datetime.datetime`,
* a :class:`str` of any format recognized by
:func:`dateutil.parser.parse`,
* or a :class:`float` or :class:`int` representing a POSIX
timestamp.
"""
for arg in args:
if isinstance(arg, dict):
for key, value in arg.items():
self[key] = value
elif isinstance(arg, list):
for item in arg:
self[item] = "Holiday"
else:
self[arg] = "Holiday"
| (self, *args: Union[Dict[Union[datetime.date, datetime.datetime, str, float, int], str], List[Union[datetime.date, datetime.datetime, str, float, int]], datetime.date, datetime.datetime, str, float, int]) -> NoneType |
39,790 | holidays.holiday_base | HolidaySum |
Returns a :class:`dict`-like object resulting from the addition of two or
more individual dictionaries of public holidays. The original dictionaries
are available as a :class:`list` in the attribute :attr:`holidays,` and
:attr:`country` and :attr:`subdiv` attributes are added
together and could become :class:`list` s. Holiday names, when different,
are merged. All years are calculated (expanded) for all operands.
| class HolidaySum(HolidayBase):
"""
Returns a :class:`dict`-like object resulting from the addition of two or
more individual dictionaries of public holidays. The original dictionaries
are available as a :class:`list` in the attribute :attr:`holidays,` and
:attr:`country` and :attr:`subdiv` attributes are added
together and could become :class:`list` s. Holiday names, when different,
are merged. All years are calculated (expanded) for all operands.
"""
country: Union[str, List[str]] # type: ignore[assignment]
"""Countries included in the addition."""
market: Union[str, List[str]] # type: ignore[assignment]
"""Markets included in the addition."""
subdiv: Optional[Union[str, List[str]]] # type: ignore[assignment]
"""Subdivisions included in the addition."""
holidays: List[HolidayBase]
"""The original HolidayBase objects included in the addition."""
years: Set[int]
"""The years calculated."""
def __init__(
self, h1: Union[HolidayBase, "HolidaySum"], h2: Union[HolidayBase, "HolidaySum"]
) -> None:
"""
:param h1:
The first HolidayBase object to add.
:param h2:
The other HolidayBase object to add.
Example:
>>> from holidays import country_holidays
>>> nafta_holidays = country_holidays('US', years=2020) + \
country_holidays('CA') + country_holidays('MX')
>>> dates = sorted(nafta_holidays.items(), key=lambda x: x[0])
>>> from pprint import pprint
>>> pprint(dates[:10], width=72)
[(datetime.date(2020, 1, 1), "Año Nuevo"),
(datetime.date(2020, 1, 20), 'Martin Luther King Jr. Day'),
(datetime.date(2020, 2, 3),
'Día de la Constitución'),
(datetime.date(2020, 2, 17), "Washington's Birthday, Family Day"),
(datetime.date(2020, 3, 16),
"Natalicio de Benito Juárez"),
(datetime.date(2020, 4, 10), 'Good Friday'),
(datetime.date(2020, 5, 1), 'Día del Trabajo'),
(datetime.date(2020, 5, 18), 'Victoria Day')]
"""
# Store originals in the holidays attribute.
self.holidays = []
for operand in (h1, h2):
if isinstance(operand, HolidaySum):
self.holidays.extend(operand.holidays)
else:
self.holidays.append(operand)
kwargs: Dict[str, Any] = {}
# Join years, expand and observed.
kwargs["years"] = h1.years | h2.years
kwargs["expand"] = h1.expand or h2.expand
kwargs["observed"] = h1.observed or h2.observed
# Join country and subdivisions data.
# TODO: this way makes no sense: joining Italy Catania (IT, CA) with
# USA Mississippi (US, MS) and USA Michigan (US, MI) yields
# country=["IT", "US"] and subdiv=["CA", "MS", "MI"], which could very
# well be California and Messina and Milano, or Catania, Mississippi
# and Milano, or ... you get the picture.
# Same goes when countries and markets are being mixed (working, yet
# still nonsensical).
for attr in ("country", "market", "subdiv"):
if (
getattr(h1, attr, None)
and getattr(h2, attr, None)
and getattr(h1, attr) != getattr(h2, attr)
):
a1 = (
getattr(h1, attr)
if isinstance(getattr(h1, attr), list)
else [getattr(h1, attr)]
)
a2 = (
getattr(h2, attr)
if isinstance(getattr(h2, attr), list)
else [getattr(h2, attr)]
)
value = a1 + a2
else:
value = getattr(h1, attr, None) or getattr(h2, attr, None)
if attr == "subdiv":
kwargs[attr] = value
else:
setattr(self, attr, value)
HolidayBase.__init__(self, **kwargs)
def _populate(self, year):
for operand in self.holidays:
operand._populate(year)
self.update(cast("Dict[DateLike, str]", operand))
| (h1: Union[holidays.holiday_base.HolidayBase, ForwardRef('HolidaySum')], h2: Union[holidays.holiday_base.HolidayBase, ForwardRef('HolidaySum')]) -> None |
39,797 | holidays.holiday_base | __init__ |
:param h1:
The first HolidayBase object to add.
:param h2:
The other HolidayBase object to add.
Example:
>>> from holidays import country_holidays
>>> nafta_holidays = country_holidays('US', years=2020) + country_holidays('CA') + country_holidays('MX')
>>> dates = sorted(nafta_holidays.items(), key=lambda x: x[0])
>>> from pprint import pprint
>>> pprint(dates[:10], width=72)
[(datetime.date(2020, 1, 1), "Año Nuevo"),
(datetime.date(2020, 1, 20), 'Martin Luther King Jr. Day'),
(datetime.date(2020, 2, 3),
'Día de la Constitución'),
(datetime.date(2020, 2, 17), "Washington's Birthday, Family Day"),
(datetime.date(2020, 3, 16),
"Natalicio de Benito Juárez"),
(datetime.date(2020, 4, 10), 'Good Friday'),
(datetime.date(2020, 5, 1), 'Día del Trabajo'),
(datetime.date(2020, 5, 18), 'Victoria Day')]
| def __init__(
self, h1: Union[HolidayBase, "HolidaySum"], h2: Union[HolidayBase, "HolidaySum"]
) -> None:
"""
:param h1:
The first HolidayBase object to add.
:param h2:
The other HolidayBase object to add.
Example:
>>> from holidays import country_holidays
>>> nafta_holidays = country_holidays('US', years=2020) + \
country_holidays('CA') + country_holidays('MX')
>>> dates = sorted(nafta_holidays.items(), key=lambda x: x[0])
>>> from pprint import pprint
>>> pprint(dates[:10], width=72)
[(datetime.date(2020, 1, 1), "Año Nuevo"),
(datetime.date(2020, 1, 20), 'Martin Luther King Jr. Day'),
(datetime.date(2020, 2, 3),
'Día de la Constitución'),
(datetime.date(2020, 2, 17), "Washington's Birthday, Family Day"),
(datetime.date(2020, 3, 16),
"Natalicio de Benito Juárez"),
(datetime.date(2020, 4, 10), 'Good Friday'),
(datetime.date(2020, 5, 1), 'Día del Trabajo'),
(datetime.date(2020, 5, 18), 'Victoria Day')]
"""
# Store originals in the holidays attribute.
self.holidays = []
for operand in (h1, h2):
if isinstance(operand, HolidaySum):
self.holidays.extend(operand.holidays)
else:
self.holidays.append(operand)
kwargs: Dict[str, Any] = {}
# Join years, expand and observed.
kwargs["years"] = h1.years | h2.years
kwargs["expand"] = h1.expand or h2.expand
kwargs["observed"] = h1.observed or h2.observed
# Join country and subdivisions data.
# TODO: this way makes no sense: joining Italy Catania (IT, CA) with
# USA Mississippi (US, MS) and USA Michigan (US, MI) yields
# country=["IT", "US"] and subdiv=["CA", "MS", "MI"], which could very
# well be California and Messina and Milano, or Catania, Mississippi
# and Milano, or ... you get the picture.
# Same goes when countries and markets are being mixed (working, yet
# still nonsensical).
for attr in ("country", "market", "subdiv"):
if (
getattr(h1, attr, None)
and getattr(h2, attr, None)
and getattr(h1, attr) != getattr(h2, attr)
):
a1 = (
getattr(h1, attr)
if isinstance(getattr(h1, attr), list)
else [getattr(h1, attr)]
)
a2 = (
getattr(h2, attr)
if isinstance(getattr(h2, attr), list)
else [getattr(h2, attr)]
)
value = a1 + a2
else:
value = getattr(h1, attr, None) or getattr(h2, attr, None)
if attr == "subdiv":
kwargs[attr] = value
else:
setattr(self, attr, value)
HolidayBase.__init__(self, **kwargs)
| (self, h1: Union[holidays.holiday_base.HolidayBase, holidays.holiday_base.HolidaySum], h2: Union[holidays.holiday_base.HolidayBase, holidays.holiday_base.HolidaySum]) -> NoneType |
39,818 | holidays.holiday_base | _populate | null | def _populate(self, year):
for operand in self.holidays:
operand._populate(year)
self.update(cast("Dict[DateLike, str]", operand))
| (self, year) |
39,834 | holidays.utils | country_holidays |
Returns a new dictionary-like :py:class:`HolidayBase` object for the public
holidays of the country matching **country** and other keyword arguments.
:param country:
An ISO 3166-1 Alpha-2 country code.
:param subdiv:
The subdivision (e.g. state or province) as a ISO 3166-2 code
or its alias; not implemented for all countries (see documentation).
:param years:
The year(s) to pre-calculate public holidays for at instantiation.
:param expand:
Whether the entire year is calculated when one date from that year
is requested.
:param observed:
Whether to include the dates of when public holiday are observed
(e.g. a holiday falling on a Sunday being observed the following
Monday). False may not work for all countries.
:param prov:
*deprecated* use subdiv instead.
:param state:
*deprecated* use subdiv instead.
:param language:
The language which the returned holiday names will be translated
into. It must be an ISO 639-1 (2-letter) language code. If the
language translation is not supported the original holiday names
will be used.
:param categories:
Requested holiday categories.
:return:
A :py:class:`HolidayBase` object matching the **country**.
The key of the :class:`dict`-like :class:`HolidayBase` object is the
`date` of the holiday, and the value is the name of the holiday itself.
Dates where a key is not present are not public holidays (or, if
**observed** is False, days when a public holiday is observed).
When passing the `date` as a key, the `date` can be expressed in one of the
following types:
* :class:`datetime.date`,
* :class:`datetime.datetime`,
* a :class:`str` of any format recognized by :func:`dateutil.parser.parse`,
* or a :class:`float` or :class:`int` representing a POSIX timestamp.
The key is always returned as a :class:`datetime.date` object.
To maximize speed, the list of public holidays is built on the fly as
needed, one calendar year at a time. When the object is instantiated
without a **years** parameter, it is empty, but, unless **expand** is set
to False, as soon as a key is accessed the class will calculate that entire
year's list of holidays and set the keys with them.
If you need to list the holidays as opposed to querying individual dates,
instantiate the class with the **years** parameter.
Example usage:
>>> from holidays import country_holidays
>>> us_holidays = country_holidays('US')
# For a specific subdivision (e.g. state or province):
>>> calif_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 :class:`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 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, 4), 'Independence Day')
(datetime.date(2020, 7, 3), 'Independence Day (observed)')
(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')
(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:
* a :class:`dict` with date/name key/value pairs (e.g.
``{'2010-07-10': 'My birthday!'}``),
* a list of dates (as a :class:`datetime.date`, :class:`datetime.datetime`,
:class:`str`, :class:`int`, or :class:`float`); ``'Holiday'`` will be
used as a description,
* or a single date item (of one of the types above); ``'Holiday'`` will be
used as a description:
>>> 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 more complex logic, like 4th Monday of January, you can inherit the
:class:`HolidayBase` class and define your own :meth:`_populate` method.
See documentation for examples.
| def country_holidays(
country: str,
subdiv: Optional[str] = None,
years: Optional[Union[int, Iterable[int]]] = None,
expand: bool = True,
observed: bool = True,
prov: Optional[str] = None,
state: Optional[str] = None,
language: Optional[str] = None,
categories: Optional[Tuple[str]] = None,
) -> HolidayBase:
"""
Returns a new dictionary-like :py:class:`HolidayBase` object for the public
holidays of the country matching **country** and other keyword arguments.
:param country:
An ISO 3166-1 Alpha-2 country code.
:param subdiv:
The subdivision (e.g. state or province) as a ISO 3166-2 code
or its alias; not implemented for all countries (see documentation).
:param years:
The year(s) to pre-calculate public holidays for at instantiation.
:param expand:
Whether the entire year is calculated when one date from that year
is requested.
:param observed:
Whether to include the dates of when public holiday are observed
(e.g. a holiday falling on a Sunday being observed the following
Monday). False may not work for all countries.
:param prov:
*deprecated* use subdiv instead.
:param state:
*deprecated* use subdiv instead.
:param language:
The language which the returned holiday names will be translated
into. It must be an ISO 639-1 (2-letter) language code. If the
language translation is not supported the original holiday names
will be used.
:param categories:
Requested holiday categories.
:return:
A :py:class:`HolidayBase` object matching the **country**.
The key of the :class:`dict`-like :class:`HolidayBase` object is the
`date` of the holiday, and the value is the name of the holiday itself.
Dates where a key is not present are not public holidays (or, if
**observed** is False, days when a public holiday is observed).
When passing the `date` as a key, the `date` can be expressed in one of the
following types:
* :class:`datetime.date`,
* :class:`datetime.datetime`,
* a :class:`str` of any format recognized by :func:`dateutil.parser.parse`,
* or a :class:`float` or :class:`int` representing a POSIX timestamp.
The key is always returned as a :class:`datetime.date` object.
To maximize speed, the list of public holidays is built on the fly as
needed, one calendar year at a time. When the object is instantiated
without a **years** parameter, it is empty, but, unless **expand** is set
to False, as soon as a key is accessed the class will calculate that entire
year's list of holidays and set the keys with them.
If you need to list the holidays as opposed to querying individual dates,
instantiate the class with the **years** parameter.
Example usage:
>>> from holidays import country_holidays
>>> us_holidays = country_holidays('US')
# For a specific subdivision (e.g. state or province):
>>> calif_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 :class:`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 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, 4), 'Independence Day')
(datetime.date(2020, 7, 3), 'Independence Day (observed)')
(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')
(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:
* a :class:`dict` with date/name key/value pairs (e.g.
``{'2010-07-10': 'My birthday!'}``),
* a list of dates (as a :class:`datetime.date`, :class:`datetime.datetime`,
:class:`str`, :class:`int`, or :class:`float`); ``'Holiday'`` will be
used as a description,
* or a single date item (of one of the types above); ``'Holiday'`` will be
used as a description:
>>> 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 more complex logic, like 4th Monday of January, you can inherit the
:class:`HolidayBase` class and define your own :meth:`_populate` method.
See documentation for examples.
"""
import holidays
try:
return getattr(holidays, country)(
years=years,
subdiv=subdiv,
expand=expand,
observed=observed,
prov=prov,
state=state,
language=language,
categories=categories,
)
except AttributeError:
raise NotImplementedError(f"Country {country} not available")
| (country: str, subdiv: Optional[str] = None, years: Union[int, Iterable[int], NoneType] = None, expand: bool = True, observed: bool = True, prov: Optional[str] = None, state: Optional[str] = None, language: Optional[str] = None, categories: Optional[Tuple[str]] = None) -> holidays.holiday_base.HolidayBase |
39,835 | holidays.utils | financial_holidays |
Returns a new dictionary-like :py:class:`HolidayBase` object for the public
holidays of the financial market matching **market** and other keyword
arguments.
:param market:
An ISO 3166-1 Alpha-2 market code.
:param subdiv:
Currently not implemented for markets (see documentation).
:param years:
The year(s) to pre-calculate public holidays for at instantiation.
:param expand:
Whether the entire year is calculated when one date from that year
is requested.
:param observed:
Whether to include the dates of when public holiday are observed
(e.g. a holiday falling on a Sunday being observed the following
Monday). False may not work for all countries.
:param language:
The language which the returned holiday names will be translated
into. It must be an ISO 639-1 (2-letter) language code. If the
language translation is not supported the original holiday names
will be used.
:return:
A :py:class:`HolidayBase` object matching the **market**.
Example usage:
>>> from holidays import financial_holidays
>>> nyse_holidays = financial_holidays('NYSE')
See :py:func:`country_holidays` documentation for further details and
examples.
| def financial_holidays(
market: str,
subdiv: Optional[str] = None,
years: Optional[Union[int, Iterable[int]]] = None,
expand: bool = True,
observed: bool = True,
language: Optional[str] = None,
) -> HolidayBase:
"""
Returns a new dictionary-like :py:class:`HolidayBase` object for the public
holidays of the financial market matching **market** and other keyword
arguments.
:param market:
An ISO 3166-1 Alpha-2 market code.
:param subdiv:
Currently not implemented for markets (see documentation).
:param years:
The year(s) to pre-calculate public holidays for at instantiation.
:param expand:
Whether the entire year is calculated when one date from that year
is requested.
:param observed:
Whether to include the dates of when public holiday are observed
(e.g. a holiday falling on a Sunday being observed the following
Monday). False may not work for all countries.
:param language:
The language which the returned holiday names will be translated
into. It must be an ISO 639-1 (2-letter) language code. If the
language translation is not supported the original holiday names
will be used.
:return:
A :py:class:`HolidayBase` object matching the **market**.
Example usage:
>>> from holidays import financial_holidays
>>> nyse_holidays = financial_holidays('NYSE')
See :py:func:`country_holidays` documentation for further details and
examples.
"""
import holidays
try:
return getattr(holidays, market)(
years=years,
subdiv=subdiv,
expand=expand,
observed=observed,
language=language,
)
except AttributeError:
raise NotImplementedError(f"Financial market {market} not available")
| (market: str, subdiv: Optional[str] = None, years: Union[int, Iterable[int], NoneType] = None, expand: bool = True, observed: bool = True, language: Optional[str] = None) -> holidays.holiday_base.HolidayBase |
39,840 | git_remote_codecommit | Context |
Repository information the hook concerns, derived from git's remote url and
the user's AWS profile.
:var botocore.session.Session session: aws session context
:var str repository: repository name
:var str version: protocol version for this hook
:var str region: region the repository resides within
:var botocore.credentials credentials: session credentials
| class Context(collections.namedtuple('Context', ['session', 'repository', 'version', 'region', 'credentials'])):
"""
Repository information the hook concerns, derived from git's remote url and
the user's AWS profile.
:var botocore.session.Session session: aws session context
:var str repository: repository name
:var str version: protocol version for this hook
:var str region: region the repository resides within
:var botocore.credentials credentials: session credentials
"""
@staticmethod
def from_url(remote_url):
"""
Parses repository information from a git url, filling in additional
attributes we need from our AWS profile.
Our remote helper accepts two distinct types of urls...
* codecommit://<profile>@<repository>
* codecommit::<region>://<profile>@<repository>
If provided the former we get the whole url, but if the later git will
truncate the proceeding 'codecommit::' prefix for us.
The '<profile>@' url is optional, using the aws sessions present profile
if not provided.
:param str remote_url: git remote url to parse
:returns: **Context** with our CodeCommit repository information
:raises:
* **FormatError** if the url is malformed
* **ProfileNotFound** if the url references a profile that doesn't exist
* **RegionNotFound** if the url references a region that doesn't exist
* **RegionNotAvailable** if the url references a region that is not available
"""
url = urlparse(remote_url)
event_handler = botocore.hooks.HierarchicalEmitter()
profile = 'default'
repository = url.netloc
if not url.scheme or not url.netloc:
raise FormatError('The following URL is malformed: {}. A URL must be in one of the two following formats: codecommit://<profile>@<repository> or codecommit::<region>://<profile>@<repository>'.format(remote_url))
if '@' in url.netloc:
profile, repository = url.netloc.split('@', 1)
session = botocore.session.Session(profile = profile, event_hooks = event_handler)
if profile not in session.available_profiles:
raise ProfileNotFound('The following profile was not found: {}. Available profiles are: {}. Either use one of the available profiles, or create an AWS CLI profile to use and then try again. For more information, see Configure an AWS CLI Profile in the AWS CLI User Guide.'.format(profile, ', '.join(session.available_profiles)))
else:
session = botocore.session.Session(event_hooks = event_handler)
session.get_component('credential_provider').get_provider('assume-role').cache = JSONFileCache()
try:
# when the aws cli is available support plugin authentication
import awscli.plugin
awscli.plugin.load_plugins(
session.full_config.get('plugins', {}),
event_hooks = event_handler,
include_builtins = False,
)
session.emit_first_non_none_response('session-initialized', session = session)
except ImportError:
pass
available_regions = [region for partition in session.get_available_partitions() for region in session.get_available_regions('codecommit', partition)]
if url.scheme == 'codecommit':
region = session.get_config_variable('region')
if not region:
raise RegionNotFound('The following profile does not have an AWS Region: {}. You must set an AWS Region for this profile. For more information, see Configure An AWS CLI Profile in the AWS CLI User Guide.'.format(profile))
if region not in available_regions:
raise RegionNotAvailable('The following AWS Region is not available for use with AWS CodeCommit: {}. For more information about CodeCommit\'s availability in AWS Regions, see the AWS CodeCommit User Guide. If an AWS Region is listed as supported but you receive this error, try updating your version of the AWS CLI or the AWS SDKs.'.format(region))
elif re.match(r"^[a-z]{2}-\w*.*-\d{1}", url.scheme):
if url.scheme in available_regions:
region = url.scheme
else:
raise RegionNotAvailable('The following AWS Region is not available for use with AWS CodeCommit: {}. For more information about CodeCommit\'s availability in AWS Regions, see the AWS CodeCommit User Guide. If an AWS Region is listed as supported but you receive this error, try updating your version of the AWS CLI or the AWS SDKs.'.format(url.scheme))
else:
raise FormatError('The following URL is malformed: {}. A URL must be in one of the two following formats: codecommit://<profile>@<repository> or codecommit::<region>://<profile>@<repository>'.format(remote_url))
credentials = session.get_credentials()
if not credentials:
raise CredentialsNotFound('The following profile does not have credentials configured: {}. You must configure the access key and secret key for the profile. For more information, see Configure an AWS CLI Profile in the AWS CLI User Guide.'.format(profile))
return Context(session, repository, 'v1', region, credentials)
| (session, repository, version, region, credentials) |
39,842 | namedtuple_Context | __new__ | Create new instance of Context(session, repository, version, region, credentials) | from builtins import function
| (_cls, session, repository, version, region, credentials) |
39,845 | collections | _replace | Return a new Context object replacing specified fields with new values | def namedtuple(typename, field_names, *, rename=False, defaults=None, module=None):
"""Returns a new subclass of tuple with named fields.
>>> Point = namedtuple('Point', ['x', 'y'])
>>> Point.__doc__ # docstring for the new class
'Point(x, y)'
>>> p = Point(11, y=22) # instantiate with positional args or keywords
>>> p[0] + p[1] # indexable like a plain tuple
33
>>> x, y = p # unpack like a regular tuple
>>> x, y
(11, 22)
>>> p.x + p.y # fields also accessible by name
33
>>> d = p._asdict() # convert to a dictionary
>>> d['x']
11
>>> Point(**d) # convert from a dictionary
Point(x=11, y=22)
>>> p._replace(x=100) # _replace() is like str.replace() but targets named fields
Point(x=100, y=22)
"""
# Validate the field names. At the user's option, either generate an error
# message or automatically replace the field name with a valid name.
if isinstance(field_names, str):
field_names = field_names.replace(',', ' ').split()
field_names = list(map(str, field_names))
typename = _sys.intern(str(typename))
if rename:
seen = set()
for index, name in enumerate(field_names):
if (not name.isidentifier()
or _iskeyword(name)
or name.startswith('_')
or name in seen):
field_names[index] = f'_{index}'
seen.add(name)
for name in [typename] + field_names:
if type(name) is not str:
raise TypeError('Type names and field names must be strings')
if not name.isidentifier():
raise ValueError('Type names and field names must be valid '
f'identifiers: {name!r}')
if _iskeyword(name):
raise ValueError('Type names and field names cannot be a '
f'keyword: {name!r}')
seen = set()
for name in field_names:
if name.startswith('_') and not rename:
raise ValueError('Field names cannot start with an underscore: '
f'{name!r}')
if name in seen:
raise ValueError(f'Encountered duplicate field name: {name!r}')
seen.add(name)
field_defaults = {}
if defaults is not None:
defaults = tuple(defaults)
if len(defaults) > len(field_names):
raise TypeError('Got more default values than field names')
field_defaults = dict(reversed(list(zip(reversed(field_names),
reversed(defaults)))))
# Variables used in the methods and docstrings
field_names = tuple(map(_sys.intern, field_names))
num_fields = len(field_names)
arg_list = ', '.join(field_names)
if num_fields == 1:
arg_list += ','
repr_fmt = '(' + ', '.join(f'{name}=%r' for name in field_names) + ')'
tuple_new = tuple.__new__
_dict, _tuple, _len, _map, _zip = dict, tuple, len, map, zip
# Create all the named tuple methods to be added to the class namespace
namespace = {
'_tuple_new': tuple_new,
'__builtins__': {},
'__name__': f'namedtuple_{typename}',
}
code = f'lambda _cls, {arg_list}: _tuple_new(_cls, ({arg_list}))'
__new__ = eval(code, namespace)
__new__.__name__ = '__new__'
__new__.__doc__ = f'Create new instance of {typename}({arg_list})'
if defaults is not None:
__new__.__defaults__ = defaults
@classmethod
def _make(cls, iterable):
result = tuple_new(cls, iterable)
if _len(result) != num_fields:
raise TypeError(f'Expected {num_fields} arguments, got {len(result)}')
return result
_make.__func__.__doc__ = (f'Make a new {typename} object from a sequence '
'or iterable')
def _replace(self, /, **kwds):
result = self._make(_map(kwds.pop, field_names, self))
if kwds:
raise ValueError(f'Got unexpected field names: {list(kwds)!r}')
return result
_replace.__doc__ = (f'Return a new {typename} object replacing specified '
'fields with new values')
def __repr__(self):
'Return a nicely formatted representation string'
return self.__class__.__name__ + repr_fmt % self
def _asdict(self):
'Return a new dict which maps field names to their values.'
return _dict(_zip(self._fields, self))
def __getnewargs__(self):
'Return self as a plain tuple. Used by copy and pickle.'
return _tuple(self)
# Modify function metadata to help with introspection and debugging
for method in (
__new__,
_make.__func__,
_replace,
__repr__,
_asdict,
__getnewargs__,
):
method.__qualname__ = f'{typename}.{method.__name__}'
# Build-up the class namespace dictionary
# and use type() to build the result class
class_namespace = {
'__doc__': f'{typename}({arg_list})',
'__slots__': (),
'_fields': field_names,
'_field_defaults': field_defaults,
'__new__': __new__,
'_make': _make,
'_replace': _replace,
'__repr__': __repr__,
'_asdict': _asdict,
'__getnewargs__': __getnewargs__,
'__match_args__': field_names,
}
for index, name in enumerate(field_names):
doc = _sys.intern(f'Alias for field number {index}')
class_namespace[name] = _tuplegetter(index, doc)
result = type(typename, (tuple,), class_namespace)
# For pickling to work, the __module__ variable needs to be set to the frame
# where the named tuple is created. Bypass this step in environments where
# sys._getframe is not defined (Jython for example) or sys._getframe is not
# defined for arguments greater than 0 (IronPython), or where the user has
# specified a particular module.
if module is None:
try:
module = _sys._getframe(1).f_globals.get('__name__', '__main__')
except (AttributeError, ValueError):
pass
if module is not None:
result.__module__ = module
return result
| (self, /, **kwds) |
39,846 | git_remote_codecommit | from_url |
Parses repository information from a git url, filling in additional
attributes we need from our AWS profile.
Our remote helper accepts two distinct types of urls...
* codecommit://<profile>@<repository>
* codecommit::<region>://<profile>@<repository>
If provided the former we get the whole url, but if the later git will
truncate the proceeding 'codecommit::' prefix for us.
The '<profile>@' url is optional, using the aws sessions present profile
if not provided.
:param str remote_url: git remote url to parse
:returns: **Context** with our CodeCommit repository information
:raises:
* **FormatError** if the url is malformed
* **ProfileNotFound** if the url references a profile that doesn't exist
* **RegionNotFound** if the url references a region that doesn't exist
* **RegionNotAvailable** if the url references a region that is not available
| @staticmethod
def from_url(remote_url):
"""
Parses repository information from a git url, filling in additional
attributes we need from our AWS profile.
Our remote helper accepts two distinct types of urls...
* codecommit://<profile>@<repository>
* codecommit::<region>://<profile>@<repository>
If provided the former we get the whole url, but if the later git will
truncate the proceeding 'codecommit::' prefix for us.
The '<profile>@' url is optional, using the aws sessions present profile
if not provided.
:param str remote_url: git remote url to parse
:returns: **Context** with our CodeCommit repository information
:raises:
* **FormatError** if the url is malformed
* **ProfileNotFound** if the url references a profile that doesn't exist
* **RegionNotFound** if the url references a region that doesn't exist
* **RegionNotAvailable** if the url references a region that is not available
"""
url = urlparse(remote_url)
event_handler = botocore.hooks.HierarchicalEmitter()
profile = 'default'
repository = url.netloc
if not url.scheme or not url.netloc:
raise FormatError('The following URL is malformed: {}. A URL must be in one of the two following formats: codecommit://<profile>@<repository> or codecommit::<region>://<profile>@<repository>'.format(remote_url))
if '@' in url.netloc:
profile, repository = url.netloc.split('@', 1)
session = botocore.session.Session(profile = profile, event_hooks = event_handler)
if profile not in session.available_profiles:
raise ProfileNotFound('The following profile was not found: {}. Available profiles are: {}. Either use one of the available profiles, or create an AWS CLI profile to use and then try again. For more information, see Configure an AWS CLI Profile in the AWS CLI User Guide.'.format(profile, ', '.join(session.available_profiles)))
else:
session = botocore.session.Session(event_hooks = event_handler)
session.get_component('credential_provider').get_provider('assume-role').cache = JSONFileCache()
try:
# when the aws cli is available support plugin authentication
import awscli.plugin
awscli.plugin.load_plugins(
session.full_config.get('plugins', {}),
event_hooks = event_handler,
include_builtins = False,
)
session.emit_first_non_none_response('session-initialized', session = session)
except ImportError:
pass
available_regions = [region for partition in session.get_available_partitions() for region in session.get_available_regions('codecommit', partition)]
if url.scheme == 'codecommit':
region = session.get_config_variable('region')
if not region:
raise RegionNotFound('The following profile does not have an AWS Region: {}. You must set an AWS Region for this profile. For more information, see Configure An AWS CLI Profile in the AWS CLI User Guide.'.format(profile))
if region not in available_regions:
raise RegionNotAvailable('The following AWS Region is not available for use with AWS CodeCommit: {}. For more information about CodeCommit\'s availability in AWS Regions, see the AWS CodeCommit User Guide. If an AWS Region is listed as supported but you receive this error, try updating your version of the AWS CLI or the AWS SDKs.'.format(region))
elif re.match(r"^[a-z]{2}-\w*.*-\d{1}", url.scheme):
if url.scheme in available_regions:
region = url.scheme
else:
raise RegionNotAvailable('The following AWS Region is not available for use with AWS CodeCommit: {}. For more information about CodeCommit\'s availability in AWS Regions, see the AWS CodeCommit User Guide. If an AWS Region is listed as supported but you receive this error, try updating your version of the AWS CLI or the AWS SDKs.'.format(url.scheme))
else:
raise FormatError('The following URL is malformed: {}. A URL must be in one of the two following formats: codecommit://<profile>@<repository> or codecommit::<region>://<profile>@<repository>'.format(remote_url))
credentials = session.get_credentials()
if not credentials:
raise CredentialsNotFound('The following profile does not have credentials configured: {}. You must configure the access key and secret key for the profile. For more information, see Configure an AWS CLI Profile in the AWS CLI User Guide.'.format(profile))
return Context(session, repository, 'v1', region, credentials)
| (remote_url) |
39,847 | git_remote_codecommit | CredentialsNotFound | null | class CredentialsNotFound(Exception):
pass
| null |
39,848 | git_remote_codecommit | FormatError | null | class FormatError(Exception):
pass
| null |
39,849 | botocore.utils | JSONFileCache | JSON file cache.
This provides a dict like interface that stores JSON serializable
objects.
The objects are serialized to JSON and stored in a file. These
values can be retrieved at a later time.
| class JSONFileCache:
"""JSON file cache.
This provides a dict like interface that stores JSON serializable
objects.
The objects are serialized to JSON and stored in a file. These
values can be retrieved at a later time.
"""
CACHE_DIR = os.path.expanduser(os.path.join('~', '.aws', 'boto', 'cache'))
def __init__(self, working_dir=CACHE_DIR, dumps_func=None):
self._working_dir = working_dir
if dumps_func is None:
dumps_func = self._default_dumps
self._dumps = dumps_func
def _default_dumps(self, obj):
return json.dumps(obj, default=self._serialize_if_needed)
def __contains__(self, cache_key):
actual_key = self._convert_cache_key(cache_key)
return os.path.isfile(actual_key)
def __getitem__(self, cache_key):
"""Retrieve value from a cache key."""
actual_key = self._convert_cache_key(cache_key)
try:
with open(actual_key) as f:
return json.load(f)
except (OSError, ValueError):
raise KeyError(cache_key)
def __delitem__(self, cache_key):
actual_key = self._convert_cache_key(cache_key)
try:
key_path = Path(actual_key)
key_path.unlink()
except FileNotFoundError:
raise KeyError(cache_key)
def __setitem__(self, cache_key, value):
full_key = self._convert_cache_key(cache_key)
try:
file_content = self._dumps(value)
except (TypeError, ValueError):
raise ValueError(
f"Value cannot be cached, must be "
f"JSON serializable: {value}"
)
if not os.path.isdir(self._working_dir):
os.makedirs(self._working_dir)
with os.fdopen(
os.open(full_key, os.O_WRONLY | os.O_CREAT, 0o600), 'w'
) as f:
f.truncate()
f.write(file_content)
def _convert_cache_key(self, cache_key):
full_path = os.path.join(self._working_dir, cache_key + '.json')
return full_path
def _serialize_if_needed(self, value, iso=False):
if isinstance(value, _DatetimeClass):
if iso:
return value.isoformat()
return value.strftime('%Y-%m-%dT%H:%M:%S%Z')
return value
| (working_dir='/root/.aws/boto/cache', dumps_func=None) |
39,853 | botocore.utils | __init__ | null | def __init__(self, working_dir=CACHE_DIR, dumps_func=None):
self._working_dir = working_dir
if dumps_func is None:
dumps_func = self._default_dumps
self._dumps = dumps_func
| (self, working_dir='/root/.aws/boto/cache', dumps_func=None) |
39,858 | git_remote_codecommit | ProfileNotFound | null | class ProfileNotFound(Exception):
pass
| null |
39,859 | git_remote_codecommit | RegionNotAvailable | null | class RegionNotAvailable(Exception):
pass
| null |
39,860 | git_remote_codecommit | RegionNotFound | null | class RegionNotFound(Exception):
pass
| null |
39,864 | git_remote_codecommit | error | null | def error(msg):
sys.stderr.write('%s\n' % msg)
sys.exit(1)
| (msg) |
39,865 | git_remote_codecommit | git_url |
Provides the signed url we can use for pushing and pulling from CodeCommit...
::
https://(username):(password)@git-codecommit.(region).(website_domain)/v1/repos/(repository)
:param str repository: repository name
:param str version: protocol version for this hook
:param str region: region the repository resides within
:param botocore.credentials credentials: session credentials
:return: url we can push/pull from
| def git_url(repository, version, region, credentials):
"""
Provides the signed url we can use for pushing and pulling from CodeCommit...
::
https://(username):(password)@git-codecommit.(region).(website_domain)/v1/repos/(repository)
:param str repository: repository name
:param str version: protocol version for this hook
:param str region: region the repository resides within
:param botocore.credentials credentials: session credentials
:return: url we can push/pull from
"""
hostname = os.environ.get('CODE_COMMIT_ENDPOINT', 'git-codecommit.{}.{}'.format(region, website_domain_mapping(region)))
path = '/{}/repos/{}'.format(version, repository)
token = '%' + credentials.token if credentials.token else ''
username = botocore.compat.quote(credentials.access_key + token, safe='')
signature = sign(hostname, path, region, credentials)
return 'https://{}:{}@{}{}'.format(username, signature, hostname, path)
| (repository, version, region, credentials) |
39,866 | git_remote_codecommit | main |
Hook that can be invoked by git, providing simplified push/pull access for a
CodeCommit repository.
| def main():
"""
Hook that can be invoked by git, providing simplified push/pull access for a
CodeCommit repository.
"""
if len(sys.argv) < 3:
error('Too few arguments. This hook requires the git command and remote.')
elif len(sys.argv) > 3:
error("Too many arguments. Hook only accepts the git command and remote, but argv was: '%s'" % "', '".join(sys.argv))
git_cmd, remote_url = sys.argv[1:3]
try:
context = Context.from_url(remote_url)
authenticated_url = git_url(context.repository, context.version, context.region, context.credentials)
sys.exit(subprocess.call(['git', 'remote-http', git_cmd, authenticated_url]))
except (FormatError, ProfileNotFound, RegionNotFound, CredentialsNotFound, RegionNotAvailable) as exc:
error(str(exc))
| () |
39,869 | git_remote_codecommit | sign |
Provides a SigV4 signature for a CodeCommit url.
:param str hostname: aws hostname request is for
:param str path: resource the request is for
:param str region: region the repository resides within
:param botocore.credentials credentials: session credentials
:return: signature for the url
| def sign(hostname, path, region, credentials):
"""
Provides a SigV4 signature for a CodeCommit url.
:param str hostname: aws hostname request is for
:param str path: resource the request is for
:param str region: region the repository resides within
:param botocore.credentials credentials: session credentials
:return: signature for the url
"""
request = botocore.awsrequest.AWSRequest(method = 'GIT', url = 'https://{}{}'.format(hostname, path))
request.context['timestamp'] = datetime.datetime.utcnow().strftime('%Y%m%dT%H%M%S')
signer = botocore.auth.SigV4Auth(credentials, 'codecommit', region)
canonical_request = 'GIT\n{}\n\nhost:{}\n\nhost\n'.format(path, hostname)
string_to_sign = signer.string_to_sign(request, canonical_request)
signature = signer.signature(string_to_sign, request)
return "{}Z{}".format(request.context['timestamp'], signature)
| (hostname, path, region, credentials) |
39,873 | git_remote_codecommit | website_domain_mapping | null | def website_domain_mapping(region):
if region in ['cn-north-1', 'cn-northwest-1']:
return 'amazonaws.com.cn'
return 'amazonaws.com'
| (region) |
39,874 | fpl.fpl | FPL | The FPL class. | class FPL:
"""The FPL class."""
def __init__(self, session):
self.session = session
resp = urlopen(API_URLS["static"], context=ssl_context)
static = json.loads(resp.read().decode("utf-8"))
for k, v in static.items():
try:
v = {w["id"]: w for w in v}
except (KeyError, TypeError):
pass
setattr(self, k, v)
try:
setattr(self,
"current_gameweek",
next(event for event in static["events"]
if event["is_current"])["id"])
except StopIteration:
setattr(self, "current_gameweek", 0)
async def get_user(self, user_id=None, return_json=False):
"""Returns the user with the given ``user_id``.
Information is taken from e.g.:
https://fantasy.premierleague.com/api/entry/91928/
:param user_id: A user's ID.
:type user_id: string or int
:param return_json: (optional) Boolean. If ``True`` returns a ``dict``,
if ``False`` returns a :class:`User` object. Defaults to ``False``.
:type return_json: bool
:rtype: :class:`User` or `dict`
"""
if user_id:
assert int(user_id) > 0, "User ID must be a positive number."
else:
# If no user ID provided get it from current session
try:
user = await get_current_user(self.session)
user_id = user["player"]["entry"]
except TypeError:
raise Exception("You must log in before using `get_user` if "
"you do not provide a user ID.")
url = API_URLS["user"].format(user_id)
user = await fetch(self.session, url)
if return_json:
return user
return User(user, session=self.session)
async def get_teams(self, team_ids=None, return_json=False):
"""Returns either a list of *all* teams, or a list of teams with IDs in
the optional ``team_ids`` list.
Information is taken from:
https://fantasy.premierleague.com/api/bootstrap-static/
:param list team_ids: (optional) List containing the IDs of teams.
If not set a list of *all* teams will be returned.
:param return_json: (optional) Boolean. If ``True`` returns a list of
``dict``s, if ``False`` returns a list of :class:`Team` objects.
Defaults to ``False``.
:type return_json: bool
:rtype: list
"""
teams = getattr(self, "teams")
if team_ids:
team_ids = set(team_ids)
teams = [team for team in teams.values() if team["id"] in team_ids]
else:
teams = [team for team in teams.values()]
if return_json:
return teams
return [Team(team_information, self.session)
for team_information in teams]
async def get_team(self, team_id, return_json=False):
"""Returns the team with the given ``team_id``.
Information is taken from:
https://fantasy.premierleague.com/api/bootstrap-static/
:param team_id: A team's ID.
:type team_id: string or int
:param return_json: (optional) Boolean. If ``True`` returns a ``dict``,
if ``False`` returns a :class:`Team` object. Defaults to ``False``.
:type return_json: bool
:rtype: :class:`Team` or ``dict``
For reference here is the mapping from team ID to team name:
.. code-block:: none
1 - Arsenal
2 - Aston Villa
3 - Brentford
4 - Brighton
5 - Burnley
6 - Chelsea
7 - Crystal Palace
8 - Everton
9 - Leicester
10 - Leeds
11 - Liverpool
12 - Man City
13 - Man Utd
14 - Newcastle
15 - Norwich
16 - Southampton
17 - Spurs
18 - Watford
19 - West Ham
20 - Wolves
"""
assert 0 < int(
team_id) < 21, "Team ID must be a number between 1 and 20."
teams = getattr(self, "teams")
team = next(team for team in teams.values()
if team["id"] == int(team_id))
if return_json:
return team
return Team(team, self.session)
async def get_player_summary(self, player_id, return_json=False):
"""Returns a summary of the player with the given ``player_id``.
Information is taken from e.g.:
https://fantasy.premierleague.com/api/element-summary/1/
:param int player_id: A player's ID.
:param return_json: (optional) Boolean. If ``True`` returns a ``dict``,
if ``False`` returns a :class:`PlayerSummary` object. Defaults to
``False``.
:type return_json: bool
:rtype: :class:`PlayerSummary` or ``dict``
"""
assert int(player_id) > 0, "Player's ID must be a positive number"
url = API_URLS["player"].format(player_id)
player_summary = await fetch(self.session, url)
if return_json:
return player_summary
return PlayerSummary(player_summary)
async def get_player_summaries(self, player_ids, return_json=False):
"""Returns a list of summaries of players whose ID are
in the ``player_ids`` list.
Information is taken from e.g.:
https://fantasy.premierleague.com/api/element-summary/1/
:param list player_ids: A list of player IDs.
:param return_json: (optional) Boolean. If ``True`` returns a list of
``dict``s, if ``False`` returns a list of :class:`PlayerSummary`
objects. Defaults to ``False``.
:type return_json: bool
:rtype: list
"""
if not player_ids:
return []
tasks = [asyncio.ensure_future(
fetch(self.session, API_URLS["player"].format(player_id)))
for player_id in player_ids]
player_summaries = await asyncio.gather(*tasks)
if return_json:
return player_summaries
return [PlayerSummary(player_summary)
for player_summary in player_summaries]
async def get_player(self, player_id, players=None, include_summary=False,
return_json=False):
"""Returns the player with the given ``player_id``.
Information is taken from e.g.:
https://fantasy.premierleague.com/api/bootstrap-static/
https://fantasy.premierleague.com/api/element-summary/1/ (optional)
:param player_id: A player's ID.
:type player_id: string or int
:param list players: (optional) A list of players.
:param bool include_summary: (optional) Includes a player's summary
if ``True``.
:param return_json: (optional) Boolean. If ``True`` returns a ``dict``,
if ``False`` returns a :class:`Player` object. Defaults to
``False``.
:rtype: :class:`Player` or ``dict``
:raises ValueError: Player with ``player_id`` not found
"""
if not players:
players = getattr(self, "elements")
try:
player = next(player for player in players.values()
if player["id"] == player_id)
except StopIteration:
raise ValueError(f"Player with ID {player_id} not found")
if include_summary:
player_summary = await self.get_player_summary(
player["id"], return_json=True)
player.update(player_summary)
if return_json:
return player
return Player(player, self.session)
async def get_players(self, player_ids=None, include_summary=False,
return_json=False):
"""Returns either a list of *all* players, or a list of players whose
IDs are in the given ``player_ids`` list.
Information is taken from e.g.:
https://fantasy.premierleague.com/api/bootstrap-static/
https://fantasy.premierleague.com/api/element-summary/1/ (optional)
:param list player_ids: (optional) A list of player IDs
:param boolean include_summary: (optional) Includes a player's summary
if ``True``.
:param return_json: (optional) Boolean. If ``True`` returns a list of
``dict``s, if ``False`` returns a list of :class:`Player`
objects. Defaults to ``False``.
:type return_json: bool
:rtype: list
"""
players = getattr(self, "elements")
if not include_summary:
if player_ids:
players = [player for player in list(players.values()) if player["id"] in player_ids]
else:
players = list(players.values())
if not return_json:
players = [Player(player, self.session) for player in players]
return players
if not player_ids:
player_ids = [player["id"] for player in list(players.values())]
tasks = [asyncio.ensure_future(
self.get_player(
player_id, players, include_summary, return_json))
for player_id in player_ids]
players = await asyncio.gather(*tasks)
return players
async def get_fixture(self, fixture_id, return_json=False):
"""Returns the fixture with the given ``fixture_id``.
Information is taken from e.g.:
https://fantasy.premierleague.com/api/fixtures/
https://fantasy.premierleague.com/api/fixtures/?event=1
:param int fixture_id: The fixture's ID.
:param return_json: (optional) Boolean. If ``True`` returns a ``dict``,
if ``False`` returns a :class:`Fixture` object. Defaults to
``False``.
:type return_json: bool
:rtype: :class:`Fixture` or ``dict``
:raises ValueError: if fixture with ``fixture_id`` not found
"""
fixtures = await fetch(self.session, API_URLS["fixtures"])
try:
fixture = next(fixture for fixture in fixtures
if fixture["id"] == fixture_id)
except StopIteration:
raise ValueError(f"Fixture with ID {fixture_id} not found")
fixture_gameweek = fixture["event"]
gameweek_fixtures = await fetch(
self.session,
API_URLS["gameweek_fixtures"].format(fixture_gameweek))
try:
fixture = next(fixture for fixture in gameweek_fixtures
if fixture["id"] == fixture_id)
except StopIteration:
raise ValueError(
f"Fixture with ID {fixture_id} not found in gameweek fixtures")
if return_json:
return fixture
return Fixture(fixture)
async def get_fixtures_by_id(self, fixture_ids, return_json=False):
"""Returns a list of all fixtures with IDs included in the
`fixture_ids` list.
Information is taken from e.g.:
https://fantasy.premierleague.com/api/fixtures/
https://fantasy.premierleague.com/api/fixtures/?event=1
:param list fixture_ids: A list of fixture IDs.
:param return_json: (optional) Boolean. If ``True`` returns a list of
``dict``s, if ``False`` returns a list of :class:`Fixture`
objects. Defaults to ``False``.
:type return_json: bool
:rtype: list
"""
if not fixture_ids:
return []
fixtures = await fetch(self.session, API_URLS["fixtures"])
fixture_gameweeks = set(fixture["event"] for fixture in fixtures
if fixture["id"] in fixture_ids)
tasks = [asyncio.ensure_future(
fetch(self.session,
API_URLS["gameweek_fixtures"].format(gameweek)))
for gameweek in fixture_gameweeks]
gameweek_fixtures = await asyncio.gather(*tasks)
merged_fixtures = list(itertools.chain(*gameweek_fixtures))
fixtures = [fixture for fixture in merged_fixtures
if fixture["id"] in fixture_ids]
if return_json:
return fixtures
return [Fixture(fixture) for fixture in fixtures]
async def get_fixtures_by_gameweek(self, gameweek, return_json=False):
"""Returns a list of all fixtures of the given ``gameweek``.
Information is taken from e.g.:
https://fantasy.premierleague.com/api/fixtures/
https://fantasy.premierleague.com/api/fixtures/?event=1
:param gameweek: A gameweek.
:type gameweek: string or int
:param return_json: (optional) Boolean. If ``True`` returns a list of
``dict``s, if ``False`` returns a list of :class:`Player`
objects. Defaults to ``False``.
:type return_json: bool
:rtype: list
"""
fixtures = await fetch(self.session,
API_URLS["gameweek_fixtures"].format(gameweek))
if return_json:
return fixtures
return [Fixture(fixture) for fixture in fixtures]
async def get_fixtures(self, return_json=False):
"""Returns a list of *all* fixtures.
Information is taken from e.g.:
https://fantasy.premierleague.com/api/fixtures/
:param return_json: (optional) Boolean. If ``True`` returns a list of
``dicts``, if ``False`` returns a list of :class:`Fixture`
objects. Defaults to ``False``.
:type return_json: bool
:rtype: list
"""
task = asyncio.ensure_future(fetch(self.session, API_URLS["fixtures"]))
gameweek_fixtures = await asyncio.gather(task)
fixtures = list(itertools.chain(*gameweek_fixtures))
if return_json:
return fixtures
return [Fixture(fixture) for fixture in fixtures]
async def get_gameweek(self, gameweek_id, include_live=False,
return_json=False):
"""Returns the gameweek with the ID ``gameweek_id``.
Information is taken from e.g.:
https://fantasy.premierleague.com/api/bootstrap-static/
https://fantasy.premierleague.com/api/event/1/live/
:param int gameweek_id: A gameweek's ID.
:param bool include_live: (optional) Includes a gameweek's live data
if ``True``.
:param return_json: (optional) Boolean. If ``True`` returns a ``dict``,
if ``False`` returns a :class:`Gameweek` object. Defaults to
``False``.
:type return_json: bool
:rtype: :class:`Gameweek` or ``dict``
"""
static_gameweeks = getattr(self, "events")
try:
static_gameweek = next(
gameweek for gameweek in static_gameweeks.values() if
gameweek["id"] == gameweek_id)
except StopIteration:
raise ValueError(f"Gameweek with ID {gameweek_id} not found")
if include_live:
live_gameweek = await fetch(
self.session, API_URLS["gameweek_live"].format(gameweek_id))
# Convert element list to dict
live_gameweek["elements"] = {
element["id"]: element for element in live_gameweek["elements"]}
# Include live bonus points
if not static_gameweek["finished"]:
fixtures = await self.get_fixtures_by_gameweek(gameweek_id)
fixtures = filter(lambda f: not f.finished, fixtures)
bonus_for_gameweek = []
for fixture in fixtures:
bonus = fixture.get_bonus(provisional=True)
bonus_for_gameweek.extend(bonus["a"] + bonus["h"])
bonus_for_gameweek = {bonus["element"]: bonus["value"]
for bonus in bonus_for_gameweek}
for player_id, bonus_points in bonus_for_gameweek.items():
if live_gameweek["elements"][player_id]["stats"]["bonus"] == 0:
live_gameweek["elements"][player_id]["stats"]["bonus"] += bonus_points
live_gameweek["elements"][player_id]["stats"]["total_points"] += bonus_points
static_gameweek.update(live_gameweek)
if return_json:
return static_gameweek
return Gameweek(static_gameweek)
async def get_gameweeks(self, gameweek_ids=None, include_live=False,
return_json=False):
"""Returns either a list of *all* gamweeks, or a list of gameweeks
whose IDs are in the ``gameweek_ids`` list.
Information is taken from e.g.:
https://fantasy.premierleague.com/api/bootstrap-static/
https://fantasy.premierleague.com/api/event/1/live/
:param list gameweek_ids: (optional) A list of gameweek IDs.
:param return_json: (optional) Boolean. If ``True`` returns a list of
``dict``s, if ``False`` returns a list of :class:`Gameweek`
objects. Defaults to ``False``.
:type return_json: bool
:rtype: list
"""
if not gameweek_ids:
gameweek_ids = range(1, 39)
tasks = [asyncio.ensure_future(
self.get_gameweek(gameweek_id, include_live, return_json))
for gameweek_id in gameweek_ids]
gameweeks = await asyncio.gather(*tasks)
return gameweeks
async def get_classic_league(self, league_id, return_json=False):
"""Returns the classic league with the given ``league_id``. Requires
the user to have logged in using ``fpl.login()``.
Information is taken from e.g.:
https://fantasy.premierleague.com/api/leagues-classic/967/standings/
:param string league_id: A classic league's ID.
:type league_id: string or int
:param return_json: (optional) Boolean. If ``True`` returns a ``dict``,
if ``False`` returns a :class:`ClassicLeague` object. Defaults to
``False``.
:type return_json: bool
:rtype: :class:`ClassicLeague` or ``dict``
"""
if not logged_in(self.session):
raise Exception("User must be logged in.")
url = API_URLS["league_classic"].format(league_id)
league = await fetch(self.session, url)
if return_json:
return league
return ClassicLeague(league, session=self.session)
async def get_h2h_league(self, league_id, return_json=False):
"""Returns a `H2HLeague` object with the given `league_id`. Requires
the user to have logged in using ``fpl.login()``.
Information is taken from e.g.:
https://fantasy.premierleague.com/api/leagues-h2h-matches/league/946125/
:param league_id: A H2H league's ID.
:type league_id: string or int
:param return_json: (optional) Boolean. If ``True`` returns a ``dict``,
if ``False`` returns a :class:`H2HLeague` object. Defaults to
``False``.
:type return_json: bool
:rtype: :class:`H2HLeague` or ``dict``
"""
if not logged_in(self.session):
raise Exception("User must be logged in.")
url = API_URLS["league_h2h"].format(league_id)
league = await fetch(self.session, url)
if return_json:
return league
return H2HLeague(league, session=self.session)
async def login(self, email=None, password=None, cookie=None):
"""Returns a requests session with FPL login authentication.
:param string email: Email address for the user's Fantasy Premier
League account.
:param string password: Password for the user's Fantasy Premier League
account.
:param string cookie: Cookie extracted from the user's browser which increases
success chance when trying to log in.
"""
if not email and not password:
email = os.getenv("FPL_EMAIL", None)
password = os.getenv("FPL_PASSWORD", None)
if not email or not password:
raise ValueError("Email and password must be set")
payload = {
"login": email,
"password": password,
"app": "plfpl-web",
"redirect_uri": "https://fantasy.premierleague.com/a/login"
}
if not cookie:
cookie = os.getenv('FPL_COOKIE')
headers = {
"User-Agent": "Dalvik/2.1.0 (Linux; U; Android 5.1; PRO 5 Build/LMY47D)",
}
if cookie is not None:
headers['Cookie'] = cookie
login_url = "https://users.premierleague.com/accounts/login/"
async with self.session.post(login_url, data=payload,
ssl=ssl_context,
headers=headers) as response:
if response.status == 403:
raise Exception('403 forbidden returned by FPL API, consider setting FPL_COOKIE environment variable '
'to the cookie in your browser when logged into the fpl website.')
state = response.url.query["state"]
if state == "fail":
reason = response.url.query["reason"]
raise ValueError(f"Login not successful, reason: {reason}")
async def get_points_against(self):
"""Returns a dictionary containing the points scored against all teams
in the Premier League, split by position and location.
An example:
.. code-block:: javascript
{
"Man City": {
"all": {
"H": [3, ..., 1],
"A": [2, ..., 2]
},
"goalkeeper": {
"H": [3, ..., 3],
"A": [2, ..., 3]
},
"defender": {
"H": [1, ..., 2],
"A": [4, ..., 1]
},
"midfielder": {
"H": [2, ..., 1],
"A": [2, ..., 2]
},
"forward": {
"H": [1, ..., 2],
"A": [6, ..., 1]
}
},
...
}
:rtype: dict
"""
players = await self.get_players(
include_summary=True, return_json=True)
points_against = {}
for player in players:
position = position_converter(player["element_type"]).lower()
for fixture in player["history"]:
if fixture["minutes"] == 0:
continue
points = fixture["total_points"]
opponent = team_converter(fixture["opponent_team"])
location = "H" if fixture["was_home"] else "A"
points_against.setdefault(
opponent,
{
"all": {"H": [], "A": []},
"goalkeeper": {"H": [], "A": []},
"defender": {"H": [], "A": []},
"midfielder": {"H": [], "A": []},
"forward": {"H": [], "A": []}
}
)
points_against[opponent]["all"][location].append(points)
points_against[opponent][position][location].append(points)
return points_against
async def FDR(self):
"""Creates a new Fixture Difficulty Ranking (FDR) based on the number
of points each team gives up to players in the Fantasy Premier League.
These numbers are also between 1.0 and 5.0 to give a similar ranking
system to the official FDR.
An example:
.. code-block:: javascript
{
"Man City": {
"all": {
"H": 4.4524439427082,
"A": 5
},
"goalkeeper": {
"H": 3.6208195949129,
"A": 5
},
"defender": {
"H": 3.747999604078,
"A": 5
},
"midfielder": {
"H": 4.6103045986504,
"A": 5
},
"forward": {
"H": 5,
"A": 3.9363219561895
}
},
...,
"Arsenal": {
"all": {
"H": 3.4414041151234,
"A": 4.2904529162594
},
"goalkeeper": {
"H": 4.1106924163919,
"A": 4.3867595818815
},
"defender": {
"H": 3.6720291204673,
"A": 4.3380917450181
},
"midfielder": {
"H": 3.3537357534825,
"A": 4.0706443384718
},
"forward": {
"H": 2.5143403441683,
"A": 4.205298013245
}
}
}
:rtype: dict
"""
def average_points_against(points_against):
"""Returns a dict with the average points scored against all teams,
per position and location.
:param dict points_against: A dict containing the points scored
against each team in the Premier League.
:rtype: dict
"""
for team, positions in points_against.items():
for position in positions.values():
position["H"] = average(position["H"])
position["A"] = average(position["A"])
points_against[team] = positions
return points_against
def get_extrema(points_against):
"""Returns the extrema for each position and location.
:param dict points_against: A dict containing the points scored
against each team in the Premier League.
:rtype: dict
"""
averages = {}
for _, positions in points_against.items():
for position, average in positions.items():
averages.setdefault(position, {"H": [], "A": []})
averages[position]["H"].append(average["H"])
averages[position]["A"].append(average["A"])
for position, locations in averages.items():
min_h = min(locations["H"])
min_a = min(locations["A"])
max_h = max(locations["H"])
max_a = max(locations["A"])
averages[position]["H"] = [min_h, max_h]
averages[position]["A"] = [min_a, max_a]
return averages
def calculate_fdr(average_points, extrema):
"""Returns a dict containing the FDR for each team, which is
calculated by scaling the average points conceded per position
between 1.0 and 5.0 using the given extrema.
:param dict points_against: A dict containing the points scored
against each team in the Premier League.
:param dict extrema: A dict containing the extrema for each
position and location.
:rtype: dict
"""
for team, positions in average_points.items():
for position, locations in positions.items():
min_h, max_h = extrema[position]["H"]
min_a, max_a = extrema[position]["A"]
fdr_h = scale(locations["H"], 5.0, 1.0, min_h, max_h)
fdr_a = scale(locations["A"], 5.0, 1.0, min_a, max_a)
average_points[team][position]["H"] = fdr_h
average_points[team][position]["A"] = fdr_a
return average_points
points_against = await self.get_points_against()
average_points = average_points_against(points_against)
extrema = get_extrema(average_points)
fdr = calculate_fdr(average_points, extrema)
return fdr
| (session) |
39,875 | fpl.fpl | FDR | Creates a new Fixture Difficulty Ranking (FDR) based on the number
of points each team gives up to players in the Fantasy Premier League.
These numbers are also between 1.0 and 5.0 to give a similar ranking
system to the official FDR.
An example:
.. code-block:: javascript
{
"Man City": {
"all": {
"H": 4.4524439427082,
"A": 5
},
"goalkeeper": {
"H": 3.6208195949129,
"A": 5
},
"defender": {
"H": 3.747999604078,
"A": 5
},
"midfielder": {
"H": 4.6103045986504,
"A": 5
},
"forward": {
"H": 5,
"A": 3.9363219561895
}
},
...,
"Arsenal": {
"all": {
"H": 3.4414041151234,
"A": 4.2904529162594
},
"goalkeeper": {
"H": 4.1106924163919,
"A": 4.3867595818815
},
"defender": {
"H": 3.6720291204673,
"A": 4.3380917450181
},
"midfielder": {
"H": 3.3537357534825,
"A": 4.0706443384718
},
"forward": {
"H": 2.5143403441683,
"A": 4.205298013245
}
}
}
:rtype: dict
| fixtures = filter(lambda f: not f.finished, fixtures)
| (self) |
39,876 | fpl.fpl | __init__ | null | def __init__(self, session):
self.session = session
resp = urlopen(API_URLS["static"], context=ssl_context)
static = json.loads(resp.read().decode("utf-8"))
for k, v in static.items():
try:
v = {w["id"]: w for w in v}
except (KeyError, TypeError):
pass
setattr(self, k, v)
try:
setattr(self,
"current_gameweek",
next(event for event in static["events"]
if event["is_current"])["id"])
except StopIteration:
setattr(self, "current_gameweek", 0)
| (self, session) |
39,877 | fpl.fpl | get_classic_league | Returns the classic league with the given ``league_id``. Requires
the user to have logged in using ``fpl.login()``.
Information is taken from e.g.:
https://fantasy.premierleague.com/api/leagues-classic/967/standings/
:param string league_id: A classic league's ID.
:type league_id: string or int
:param return_json: (optional) Boolean. If ``True`` returns a ``dict``,
if ``False`` returns a :class:`ClassicLeague` object. Defaults to
``False``.
:type return_json: bool
:rtype: :class:`ClassicLeague` or ``dict``
| fixtures = filter(lambda f: not f.finished, fixtures)
| (self, league_id, return_json=False) |
39,878 | fpl.fpl | get_fixture | Returns the fixture with the given ``fixture_id``.
Information is taken from e.g.:
https://fantasy.premierleague.com/api/fixtures/
https://fantasy.premierleague.com/api/fixtures/?event=1
:param int fixture_id: The fixture's ID.
:param return_json: (optional) Boolean. If ``True`` returns a ``dict``,
if ``False`` returns a :class:`Fixture` object. Defaults to
``False``.
:type return_json: bool
:rtype: :class:`Fixture` or ``dict``
:raises ValueError: if fixture with ``fixture_id`` not found
| def __init__(self, session):
self.session = session
resp = urlopen(API_URLS["static"], context=ssl_context)
static = json.loads(resp.read().decode("utf-8"))
for k, v in static.items():
try:
v = {w["id"]: w for w in v}
except (KeyError, TypeError):
pass
setattr(self, k, v)
try:
setattr(self,
"current_gameweek",
next(event for event in static["events"]
if event["is_current"])["id"])
except StopIteration:
setattr(self, "current_gameweek", 0)
| (self, fixture_id, return_json=False) |
39,879 | fpl.fpl | get_fixtures | Returns a list of *all* fixtures.
Information is taken from e.g.:
https://fantasy.premierleague.com/api/fixtures/
:param return_json: (optional) Boolean. If ``True`` returns a list of
``dicts``, if ``False`` returns a list of :class:`Fixture`
objects. Defaults to ``False``.
:type return_json: bool
:rtype: list
| def __init__(self, session):
self.session = session
resp = urlopen(API_URLS["static"], context=ssl_context)
static = json.loads(resp.read().decode("utf-8"))
for k, v in static.items():
try:
v = {w["id"]: w for w in v}
except (KeyError, TypeError):
pass
setattr(self, k, v)
try:
setattr(self,
"current_gameweek",
next(event for event in static["events"]
if event["is_current"])["id"])
except StopIteration:
setattr(self, "current_gameweek", 0)
| (self, return_json=False) |
39,880 | fpl.fpl | get_fixtures_by_gameweek | Returns a list of all fixtures of the given ``gameweek``.
Information is taken from e.g.:
https://fantasy.premierleague.com/api/fixtures/
https://fantasy.premierleague.com/api/fixtures/?event=1
:param gameweek: A gameweek.
:type gameweek: string or int
:param return_json: (optional) Boolean. If ``True`` returns a list of
``dict``s, if ``False`` returns a list of :class:`Player`
objects. Defaults to ``False``.
:type return_json: bool
:rtype: list
| def __init__(self, session):
self.session = session
resp = urlopen(API_URLS["static"], context=ssl_context)
static = json.loads(resp.read().decode("utf-8"))
for k, v in static.items():
try:
v = {w["id"]: w for w in v}
except (KeyError, TypeError):
pass
setattr(self, k, v)
try:
setattr(self,
"current_gameweek",
next(event for event in static["events"]
if event["is_current"])["id"])
except StopIteration:
setattr(self, "current_gameweek", 0)
| (self, gameweek, return_json=False) |
39,881 | fpl.fpl | get_fixtures_by_id | Returns a list of all fixtures with IDs included in the
`fixture_ids` list.
Information is taken from e.g.:
https://fantasy.premierleague.com/api/fixtures/
https://fantasy.premierleague.com/api/fixtures/?event=1
:param list fixture_ids: A list of fixture IDs.
:param return_json: (optional) Boolean. If ``True`` returns a list of
``dict``s, if ``False`` returns a list of :class:`Fixture`
objects. Defaults to ``False``.
:type return_json: bool
:rtype: list
| def __init__(self, session):
self.session = session
resp = urlopen(API_URLS["static"], context=ssl_context)
static = json.loads(resp.read().decode("utf-8"))
for k, v in static.items():
try:
v = {w["id"]: w for w in v}
except (KeyError, TypeError):
pass
setattr(self, k, v)
try:
setattr(self,
"current_gameweek",
next(event for event in static["events"]
if event["is_current"])["id"])
except StopIteration:
setattr(self, "current_gameweek", 0)
| (self, fixture_ids, return_json=False) |
39,882 | fpl.fpl | get_gameweek | Returns the gameweek with the ID ``gameweek_id``.
Information is taken from e.g.:
https://fantasy.premierleague.com/api/bootstrap-static/
https://fantasy.premierleague.com/api/event/1/live/
:param int gameweek_id: A gameweek's ID.
:param bool include_live: (optional) Includes a gameweek's live data
if ``True``.
:param return_json: (optional) Boolean. If ``True`` returns a ``dict``,
if ``False`` returns a :class:`Gameweek` object. Defaults to
``False``.
:type return_json: bool
:rtype: :class:`Gameweek` or ``dict``
| def __init__(self, session):
self.session = session
resp = urlopen(API_URLS["static"], context=ssl_context)
static = json.loads(resp.read().decode("utf-8"))
for k, v in static.items():
try:
v = {w["id"]: w for w in v}
except (KeyError, TypeError):
pass
setattr(self, k, v)
try:
setattr(self,
"current_gameweek",
next(event for event in static["events"]
if event["is_current"])["id"])
except StopIteration:
setattr(self, "current_gameweek", 0)
| (self, gameweek_id, include_live=False, return_json=False) |
39,883 | fpl.fpl | get_gameweeks | Returns either a list of *all* gamweeks, or a list of gameweeks
whose IDs are in the ``gameweek_ids`` list.
Information is taken from e.g.:
https://fantasy.premierleague.com/api/bootstrap-static/
https://fantasy.premierleague.com/api/event/1/live/
:param list gameweek_ids: (optional) A list of gameweek IDs.
:param return_json: (optional) Boolean. If ``True`` returns a list of
``dict``s, if ``False`` returns a list of :class:`Gameweek`
objects. Defaults to ``False``.
:type return_json: bool
:rtype: list
| fixtures = filter(lambda f: not f.finished, fixtures)
| (self, gameweek_ids=None, include_live=False, return_json=False) |
39,884 | fpl.fpl | get_h2h_league | Returns a `H2HLeague` object with the given `league_id`. Requires
the user to have logged in using ``fpl.login()``.
Information is taken from e.g.:
https://fantasy.premierleague.com/api/leagues-h2h-matches/league/946125/
:param league_id: A H2H league's ID.
:type league_id: string or int
:param return_json: (optional) Boolean. If ``True`` returns a ``dict``,
if ``False`` returns a :class:`H2HLeague` object. Defaults to
``False``.
:type return_json: bool
:rtype: :class:`H2HLeague` or ``dict``
| fixtures = filter(lambda f: not f.finished, fixtures)
| (self, league_id, return_json=False) |
39,885 | fpl.fpl | get_player | Returns the player with the given ``player_id``.
Information is taken from e.g.:
https://fantasy.premierleague.com/api/bootstrap-static/
https://fantasy.premierleague.com/api/element-summary/1/ (optional)
:param player_id: A player's ID.
:type player_id: string or int
:param list players: (optional) A list of players.
:param bool include_summary: (optional) Includes a player's summary
if ``True``.
:param return_json: (optional) Boolean. If ``True`` returns a ``dict``,
if ``False`` returns a :class:`Player` object. Defaults to
``False``.
:rtype: :class:`Player` or ``dict``
:raises ValueError: Player with ``player_id`` not found
| def __init__(self, session):
self.session = session
resp = urlopen(API_URLS["static"], context=ssl_context)
static = json.loads(resp.read().decode("utf-8"))
for k, v in static.items():
try:
v = {w["id"]: w for w in v}
except (KeyError, TypeError):
pass
setattr(self, k, v)
try:
setattr(self,
"current_gameweek",
next(event for event in static["events"]
if event["is_current"])["id"])
except StopIteration:
setattr(self, "current_gameweek", 0)
| (self, player_id, players=None, include_summary=False, return_json=False) |
39,886 | fpl.fpl | get_player_summaries | Returns a list of summaries of players whose ID are
in the ``player_ids`` list.
Information is taken from e.g.:
https://fantasy.premierleague.com/api/element-summary/1/
:param list player_ids: A list of player IDs.
:param return_json: (optional) Boolean. If ``True`` returns a list of
``dict``s, if ``False`` returns a list of :class:`PlayerSummary`
objects. Defaults to ``False``.
:type return_json: bool
:rtype: list
| def __init__(self, session):
self.session = session
resp = urlopen(API_URLS["static"], context=ssl_context)
static = json.loads(resp.read().decode("utf-8"))
for k, v in static.items():
try:
v = {w["id"]: w for w in v}
except (KeyError, TypeError):
pass
setattr(self, k, v)
try:
setattr(self,
"current_gameweek",
next(event for event in static["events"]
if event["is_current"])["id"])
except StopIteration:
setattr(self, "current_gameweek", 0)
| (self, player_ids, return_json=False) |
39,887 | fpl.fpl | get_player_summary | Returns a summary of the player with the given ``player_id``.
Information is taken from e.g.:
https://fantasy.premierleague.com/api/element-summary/1/
:param int player_id: A player's ID.
:param return_json: (optional) Boolean. If ``True`` returns a ``dict``,
if ``False`` returns a :class:`PlayerSummary` object. Defaults to
``False``.
:type return_json: bool
:rtype: :class:`PlayerSummary` or ``dict``
| def __init__(self, session):
self.session = session
resp = urlopen(API_URLS["static"], context=ssl_context)
static = json.loads(resp.read().decode("utf-8"))
for k, v in static.items():
try:
v = {w["id"]: w for w in v}
except (KeyError, TypeError):
pass
setattr(self, k, v)
try:
setattr(self,
"current_gameweek",
next(event for event in static["events"]
if event["is_current"])["id"])
except StopIteration:
setattr(self, "current_gameweek", 0)
| (self, player_id, return_json=False) |
39,888 | fpl.fpl | get_players | Returns either a list of *all* players, or a list of players whose
IDs are in the given ``player_ids`` list.
Information is taken from e.g.:
https://fantasy.premierleague.com/api/bootstrap-static/
https://fantasy.premierleague.com/api/element-summary/1/ (optional)
:param list player_ids: (optional) A list of player IDs
:param boolean include_summary: (optional) Includes a player's summary
if ``True``.
:param return_json: (optional) Boolean. If ``True`` returns a list of
``dict``s, if ``False`` returns a list of :class:`Player`
objects. Defaults to ``False``.
:type return_json: bool
:rtype: list
| def __init__(self, session):
self.session = session
resp = urlopen(API_URLS["static"], context=ssl_context)
static = json.loads(resp.read().decode("utf-8"))
for k, v in static.items():
try:
v = {w["id"]: w for w in v}
except (KeyError, TypeError):
pass
setattr(self, k, v)
try:
setattr(self,
"current_gameweek",
next(event for event in static["events"]
if event["is_current"])["id"])
except StopIteration:
setattr(self, "current_gameweek", 0)
| (self, player_ids=None, include_summary=False, return_json=False) |
39,889 | fpl.fpl | get_points_against | Returns a dictionary containing the points scored against all teams
in the Premier League, split by position and location.
An example:
.. code-block:: javascript
{
"Man City": {
"all": {
"H": [3, ..., 1],
"A": [2, ..., 2]
},
"goalkeeper": {
"H": [3, ..., 3],
"A": [2, ..., 3]
},
"defender": {
"H": [1, ..., 2],
"A": [4, ..., 1]
},
"midfielder": {
"H": [2, ..., 1],
"A": [2, ..., 2]
},
"forward": {
"H": [1, ..., 2],
"A": [6, ..., 1]
}
},
...
}
:rtype: dict
| fixtures = filter(lambda f: not f.finished, fixtures)
| (self) |
39,890 | fpl.fpl | get_team | Returns the team with the given ``team_id``.
Information is taken from:
https://fantasy.premierleague.com/api/bootstrap-static/
:param team_id: A team's ID.
:type team_id: string or int
:param return_json: (optional) Boolean. If ``True`` returns a ``dict``,
if ``False`` returns a :class:`Team` object. Defaults to ``False``.
:type return_json: bool
:rtype: :class:`Team` or ``dict``
For reference here is the mapping from team ID to team name:
.. code-block:: none
1 - Arsenal
2 - Aston Villa
3 - Brentford
4 - Brighton
5 - Burnley
6 - Chelsea
7 - Crystal Palace
8 - Everton
9 - Leicester
10 - Leeds
11 - Liverpool
12 - Man City
13 - Man Utd
14 - Newcastle
15 - Norwich
16 - Southampton
17 - Spurs
18 - Watford
19 - West Ham
20 - Wolves
| def __init__(self, session):
self.session = session
resp = urlopen(API_URLS["static"], context=ssl_context)
static = json.loads(resp.read().decode("utf-8"))
for k, v in static.items():
try:
v = {w["id"]: w for w in v}
except (KeyError, TypeError):
pass
setattr(self, k, v)
try:
setattr(self,
"current_gameweek",
next(event for event in static["events"]
if event["is_current"])["id"])
except StopIteration:
setattr(self, "current_gameweek", 0)
| (self, team_id, return_json=False) |
39,891 | fpl.fpl | get_teams | Returns either a list of *all* teams, or a list of teams with IDs in
the optional ``team_ids`` list.
Information is taken from:
https://fantasy.premierleague.com/api/bootstrap-static/
:param list team_ids: (optional) List containing the IDs of teams.
If not set a list of *all* teams will be returned.
:param return_json: (optional) Boolean. If ``True`` returns a list of
``dict``s, if ``False`` returns a list of :class:`Team` objects.
Defaults to ``False``.
:type return_json: bool
:rtype: list
| def __init__(self, session):
self.session = session
resp = urlopen(API_URLS["static"], context=ssl_context)
static = json.loads(resp.read().decode("utf-8"))
for k, v in static.items():
try:
v = {w["id"]: w for w in v}
except (KeyError, TypeError):
pass
setattr(self, k, v)
try:
setattr(self,
"current_gameweek",
next(event for event in static["events"]
if event["is_current"])["id"])
except StopIteration:
setattr(self, "current_gameweek", 0)
| (self, team_ids=None, return_json=False) |
39,892 | fpl.fpl | get_user | Returns the user with the given ``user_id``.
Information is taken from e.g.:
https://fantasy.premierleague.com/api/entry/91928/
:param user_id: A user's ID.
:type user_id: string or int
:param return_json: (optional) Boolean. If ``True`` returns a ``dict``,
if ``False`` returns a :class:`User` object. Defaults to ``False``.
:type return_json: bool
:rtype: :class:`User` or `dict`
| def __init__(self, session):
self.session = session
resp = urlopen(API_URLS["static"], context=ssl_context)
static = json.loads(resp.read().decode("utf-8"))
for k, v in static.items():
try:
v = {w["id"]: w for w in v}
except (KeyError, TypeError):
pass
setattr(self, k, v)
try:
setattr(self,
"current_gameweek",
next(event for event in static["events"]
if event["is_current"])["id"])
except StopIteration:
setattr(self, "current_gameweek", 0)
| (self, user_id=None, return_json=False) |
39,893 | fpl.fpl | login | Returns a requests session with FPL login authentication.
:param string email: Email address for the user's Fantasy Premier
League account.
:param string password: Password for the user's Fantasy Premier League
account.
:param string cookie: Cookie extracted from the user's browser which increases
success chance when trying to log in.
| fixtures = filter(lambda f: not f.finished, fixtures)
| (self, email=None, password=None, cookie=None) |
39,899 | lerc._lerc | convert2ma | null | def convert2ma(npArr, npValidMask, nValuesPerPixel, nBands, npmaNoData):
if (npmaNoData is None) and (npValidMask is None):
return(np.ma.array(npArr, mask = False))
if not npValidMask is None:
if (nValuesPerPixel > 1): # need to blow up mask from 2D to 3D or 3D to 4D
npMask3D = npValidMask
for k in range(nValuesPerPixel - 1):
npMask3D = np.dstack((npMask3D, npValidMask))
if nBands == 1 or npValidMask.ndim == 3: # one mask per band
npmaArr = np.ma.array(npArr, mask = (npMask3D == False))
elif nBands > 1: # use same mask for all bands
npMask4D = np.stack([npMask3D for _ in range(nBands)])
npmaArr = np.ma.array(npArr, mask = (npMask4D == False))
elif (nValuesPerPixel == 1):
if nBands == 1 or npValidMask.ndim == 3: # one mask per band
npmaArr = np.ma.array(npArr, mask = (npValidMask == False))
elif nBands > 1: # same mask for all bands
npMask3D = np.stack([npValidMask for _ in range(nBands)])
npmaArr = np.ma.array(npArr, mask = (npMask3D == False))
elif npValidMask is None:
npmaArr = np.ma.array(npArr, mask = False)
if not npmaNoData is None:
if nBands == 1:
if not npmaNoData.mask[0]:
npmaArr = np.ma.masked_equal(npmaArr, npmaNoData[0])
elif nBands > 1:
for m in range(nBands):
if not npmaNoData.mask[m]:
npmaArr[m] = np.ma.masked_equal(npmaArr[m], npmaNoData[m])
return (npmaArr)
| (npArr, npValidMask, nValuesPerPixel, nBands, npmaNoData) |
39,901 | lerc._lerc | decode | null | def decode(lercBlob, printInfo = False):
return _decode_Ext(lercBlob, 0, printInfo)
| (lercBlob, printInfo=False) |
39,902 | lerc._lerc | decode_4D | null | def decode_4D(lercBlob, printInfo = False):
return _decode_Ext(lercBlob, 1, printInfo)
| (lercBlob, printInfo=False) |
39,903 | lerc._lerc | decode_ma | null | def decode_ma(lercBlob, printInfo = False):
fctErr = 'Error in decode_ma(): '
(result, version, dataType, nValuesPerPixel, nCols, nRows, nBands, nValidPixels,
blobSize, nMasks, zMin, zMax, maxZErrUsed, nUsesNoData) = getLercBlobInfo_4D(lercBlob, printInfo)
if result > 0:
print(fctErr, 'getLercBlobInfo() failed with error code = ', result)
return result
(result, npArr, npValidMask, npmaNoData) = _decode_Ext(lercBlob, 1, printInfo)
if result > 0:
print(fctErr, '_decode_Ext() failed with error code = ', result)
return result
npmaArr = convert2ma(npArr, npValidMask, nValuesPerPixel, nBands, npmaNoData)
return (result, npmaArr, nValuesPerPixel, npmaNoData)
| (lercBlob, printInfo=False) |
39,904 | lerc._lerc | encode | null | def encode(npArr, nValuesPerPixel, bHasMask, npValidMask, maxZErr, nBytesHint, printInfo = False):
return _encode_Ext(npArr, nValuesPerPixel, npValidMask, maxZErr, nBytesHint, None, printInfo)
| (npArr, nValuesPerPixel, bHasMask, npValidMask, maxZErr, nBytesHint, printInfo=False) |
39,905 | lerc._lerc | encode_4D | null | def encode_4D(npArr, nValuesPerPixel, npValidMask, maxZErr, nBytesHint, npmaNoDataPerBand = None, printInfo = False):
return _encode_Ext(npArr, nValuesPerPixel, npValidMask, maxZErr, nBytesHint, npmaNoDataPerBand, printInfo)
| (npArr, nValuesPerPixel, npValidMask, maxZErr, nBytesHint, npmaNoDataPerBand=None, printInfo=False) |
39,906 | lerc._lerc | encode_ma | null | def encode_ma(npmaArr, nValuesPerPixel, maxZErr, nBytesHint, npmaNoDataPerBand = None, printInfo = False):
fctErr = 'Error in encode_ma(): '
if nValuesPerPixel == 1:
return _encode_Ext(npmaArr.data, nValuesPerPixel, np.logical_not(npmaArr.mask),
maxZErr, nBytesHint, npmaNoDataPerBand, printInfo)
elif nValuesPerPixel > 1:
npArr = npmaArr.data
if npmaNoDataPerBand is not None:
# for each band that has noData value, fill all masked values with that noData value
if npmaArr.ndim == 3: # nBands == 1
if not npmaNoDataPerBand.mask[0]:
npArr = np.ma.filled(npmaArr, npmaNoDataPerBand[0])
return _encode_Ext(npArr, nValuesPerPixel, None, maxZErr, nBytesHint, npmaNoDataPerBand, printInfo)
elif npmaArr.ndim == 4: # nBands > 1
nBands = npmaNoDataPerBand.size
for m in range(nBands):
if not npmaNoDataPerBand.mask[m]:
npArr[m] = np.ma.filled(npmaArr[m], npmaNoDataPerBand[m])
if not np.any(npmaNoDataPerBand.mask):
return _encode_Ext(npArr, nValuesPerPixel, None, maxZErr, nBytesHint, npmaNoDataPerBand, printInfo)
# now we have at least one band w/o a noData value, so we must convert the mask and check there is no mixed case
# compute sum of most inner dimension,
# so that resulting array has one dim less, and values are in [0, nDepth]
intMask = np.sum(npmaArr.mask, axis = npmaArr.mask.ndim - 1, dtype = int)
# for each band without a noData value, check there is no other value but 0 or nDepth
# (ensure there is no mixed case)
if intMask.ndim == 2: # nBands == 1
if npmaNoDataPerBand.mask[0]:
uv = np.unique(intMask)
if _has_mixed_case(uv, nValuesPerPixel, 0):
return (-1, 0)
elif intMask.ndim == 3: # nBands > 1
for m in range(nBands):
if npmaNoDataPerBand.mask[m]:
uv = np.unique(intMask[m])
if _has_mixed_case(uv, nValuesPerPixel, m):
return (-1, 0)
# convert this int mask back to boolean
boolMask = intMask.astype(bool)
return _encode_Ext(npArr, nValuesPerPixel, np.logical_not(boolMask),
maxZErr, nBytesHint, npmaNoDataPerBand, printInfo)
| (npmaArr, nValuesPerPixel, maxZErr, nBytesHint, npmaNoDataPerBand=None, printInfo=False) |
39,907 | lerc._lerc | findDataRange | null | def findDataRange(npArr, bHasMask, npValidMask, nBands, printInfo = False):
if printInfo:
start = timer()
if not bHasMask or npValidMask is None:
zMin = np.amin(npArr)
zMax = np.amax(npArr)
else:
if not npValidMask.any(): # if all pixel values are void
return (-1, -1)
if nBands == 1 or npValidMask.ndim == 3: # one mask per band
zMin = np.amin(npArr[npValidMask])
zMax = np.amax(npArr[npValidMask])
elif nBands > 1: # same mask for all bands
zMin = float("inf")
zMax = -zMin
for m in range(nBands):
zMin = min(np.amin(npArr[m][npValidMask]), zMin)
zMax = max(np.amax(npArr[m][npValidMask]), zMax)
if printInfo:
end = timer()
print('time findDataRange() = ', (end - start))
return (zMin, zMax)
| (npArr, bHasMask, npValidMask, nBands, printInfo=False) |
39,908 | lerc._lerc | findDataRange_ma | null | def findDataRange_ma(npmaArr):
if not npmaArr.any():
return (-1, -1)
zMin = np.amin(npmaArr)
zMax = np.amax(npmaArr)
return (zMin, zMax)
| (npmaArr) |
39,909 | lerc._lerc | findMaxZError | null | def findMaxZError(npArr1, npArr2):
npDiff = npArr2 - npArr1
yMin = np.amin(npDiff)
yMax = np.amax(npDiff)
return max(abs(yMin), abs(yMax))
| (npArr1, npArr2) |
39,910 | lerc._lerc | findMaxZError_4D | null | def findMaxZError_4D(npDataOrig, npDataDec, npValidMaskDec, nBands):
npDiff = npDataDec - npDataOrig
if (npValidMaskDec is None):
zMin = np.amin(npDiff)
zMax = np.amax(npDiff)
else:
if not npValidMaskDec.any(): # if all pixel values are void
return 0
if nBands == 1 or npValidMaskDec.ndim == 3: # one mask per band
zMin = np.amin(npDiff[npValidMaskDec])
zMax = np.amax(npDiff[npValidMaskDec])
elif nBands > 1: # same mask for all bands
zMin = float("inf")
zMax = -zMin
for m in range(nBands):
zMin = min(np.amin(npDiff[m][npValidMaskDec]), zMin)
zMax = max(np.amax(npDiff[m][npValidMaskDec]), zMax)
return max(abs(zMin), abs(zMax))
| (npDataOrig, npDataDec, npValidMaskDec, nBands) |
39,911 | lerc._lerc | findMaxZError_ma | null | def findMaxZError_ma(npmaArrOrig, npmaArrDec):
npDiff = npmaArrDec - npmaArrOrig
yMin = np.amin(npDiff)
yMax = np.amax(npDiff)
return max(abs(yMin), abs(yMax))
| (npmaArrOrig, npmaArrDec) |
39,912 | lerc._lerc | getLercBlobInfo | null | def getLercBlobInfo(lercBlob, printInfo = False):
return _getLercBlobInfo_Ext(lercBlob, 0, printInfo)
| (lercBlob, printInfo=False) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.