Skip to content

Schedule

Schedule Class Documentation

Represents a sports league schedule, capable of handling both weekly and daily formats.

Attributes:

Name Type Description
espn_instance PYESPN

The ESPN API wrapper instance.

schedule_list list[str]

A list of URLs referencing weekly or daily schedule endpoints.

schedule_type str

The type of schedule ('pre', 'regular', or 'post').

season int

The season year, parsed from the schedule URL.

weeks list[Week]

A list of Week instances containing schedule events.

Methods:

Name Description
get_events

int) -> list[Event]: Retrieves the list of Event instances for the given week index.

_set_schedule_weekly_data

Builds the schedule using ESPN's weekly format by iterating over each week's schedule endpoint and paginating through event data.

_set_schedule_daily_data

Builds the schedule using ESPN's daily format by constructing date-based event queries for each week and paginating through all available event pages.

Source code in pyespn/classes/schedule.py
class Schedule:
    """
    Represents a sports league schedule, capable of handling both weekly and daily formats.

    Attributes:
        espn_instance (PYESPN): The ESPN API wrapper instance.
        schedule_list (list[str]): A list of URLs referencing weekly or daily schedule endpoints.
        schedule_type (str): The type of schedule ('pre', 'regular', or 'post').
        season (int): The season year, parsed from the schedule URL.
        weeks (list[Week]): A list of Week instances containing schedule events.

    Methods:
        get_events(week: int) -> list[Event]:
            Retrieves the list of Event instances for the given week index.

        _set_schedule_weekly_data() -> None:
            Builds the schedule using ESPN's weekly format by iterating over each week's schedule endpoint
            and paginating through event data.

        _set_schedule_daily_data() -> None:
            Builds the schedule using ESPN's daily format by constructing date-based event queries for
            each week and paginating through all available event pages.
    """

    def __init__(self, espn_instance, schedule_list: list,
                 load_odds: bool = False,
                 load_plays: bool = False):
        """
        Initializes the Schedule instance.

        Args:
            espn_instance (PYESPN): The ESPN API wrapper instance.
            schedule_list (list[str]): A list of URLs pointing to weekly or daily schedule endpoints.
        """
        self.schedule_list = schedule_list
        self._espn_instance = espn_instance
        self.load_odds = load_odds
        self.load_plays = load_plays
        self.api_info = self._espn_instance.api_mapping

        self.season = get_an_id(self.schedule_list[0], 'seasons')
        self.schedule_type = None
        self._weeks = []

        schedule_type_id = get_schedule_type(self.schedule_list[0])

        if schedule_type_id == 1:
            self.schedule_type = 'pre'
        elif schedule_type_id == 2:
            self.schedule_type = 'regular'
        elif schedule_type_id == 3:
            self.schedule_type = 'post'

        if self.api_info.get('schedule') == 'weekly':
            self._set_schedule_weekly_data()
        elif self.api_info.get('schedule') == 'daily':
            self._set_schedule_daily_data()
        else:
            raise ScheduleTypeUnknownError(league_abbv=self._espn_instance.league_abbv)

    @property
    def espn_instance(self):
        """
            PYESPN: the espn client instance associated with the class
        """
        return self._espn_instance

    @property
    def weeks(self):
        """
            list[Week]: a list of Week objects
        """
        return self._weeks

    def __repr__(self) -> str:
        """
        Returns a string representation of the schedule instance.

        Returns:
            str: A formatted string with the schedule.
        """
        return f"<Schedule | {self.season} {self.schedule_type} season>"

    def _set_schedule_daily_data(self) -> None:
        """
        Constructs the schedule for leagues using a daily schedule format.

        This method fetches data for each provided schedule URL and builds a list of
        events within the specified date range. Each page of event data is retrieved
        and its events are collected before constructing a Week object.
        """

        for week_url in self.schedule_list:
            api_url = week_url
            week_content = fetch_espn_data(api_url)
            start_date = datetime.strptime(week_content.get('startDate')[:10], "%Y-%m-%d")
            end_date = datetime.strptime(week_content.get('endDate')[:10], "%Y-%m-%d")
            week_number = get_an_id(url=api_url,
                                    slug='weeks')
            week_events_url = f'http://sports.core.api.espn.com/{self._espn_instance.v}/sports/{self.api_info.get("sport")}/leagues/{self.api_info.get("league")}/events?dates={start_date.strftime("%Y%m%d")}-{end_date.strftime("%Y%m%d")}'
            week_content = fetch_espn_data(week_events_url)
            week_pages = week_content.get('pageCount')
            week_events = []
            for week in range(1, week_pages + 1):
                week_page_url = week_events_url + f"&page={week}"
                week_page_content = fetch_espn_data(week_page_url)

                for event in week_page_content.get('items', []):
                    week_events.append(event.get('$ref'))
                    pass

            self._weeks.append(Week(espn_instance=self._espn_instance,
                                    week_list=week_events,
                                    week_number=week_number,
                                    start_date=start_date,
                                    end_date=end_date))

    def _set_schedule_weekly_data(self) -> None:
        """
        Constructs the schedule for leagues using a weekly schedule format.

        This method paginates through each week's event data from the ESPN API and
        assembles a list of event references to create corresponding Week instances.
        """
        for week_url in self.schedule_list:
            weekly_content = fetch_espn_data(url=week_url)
            start_date = datetime.strptime(weekly_content.get('startDate')[:10], "%Y-%m-%d")
            end_date = datetime.strptime(weekly_content.get('endDate')[:10], "%Y-%m-%d")
            api_url = week_url.split('?')[0] + f'/events'
            week_content = fetch_espn_data(api_url)
            week_pages = week_content.get('pageCount')
            week_number = get_an_id(url=api_url,
                                    slug='weeks')
            for week_page in range(1, week_pages + 1):
                weekly_url = api_url + f'?page={week_page}'
                this_week_content = fetch_espn_data(weekly_url)
                event_urls = []
                for event in this_week_content.get('items', []):
                    event_urls.append(event.get('$ref'))
                if event_urls:
                    self._weeks.append(Week(espn_instance=self._espn_instance,
                                            week_list=event_urls,
                                            week_number=week_number,
                                            start_date=start_date,
                                            end_date=end_date))

    def get_events(self, week_num: int) -> list["Event"]:
        """
        Retrieves the list of events for the specified week.

        Args:
            week_num (int): The week number to retrieve events for.

        Returns:
            list[Event]: A list of Event instances representing the scheduled games for the specified week.

        Raises:
            StopIteration: If no Week instance is found for the specified week number.
        """
        week = next((week for week in self._weeks if str(week.week_number) == str(week_num)), None)

        if week is None:
            raise ValueError(f"No events found for week number {week_num}")

        return week.events

    def to_dict(self) -> list:
        """
        Converts the Schedule instance to its original list of JSON dictionaries.

        Returns:
            list: A list of dictionaries, each representing a scheduled event or game.

        Note:
            This method returns the raw schedule data as a list of dictionaries,
            suitable for serialization or further processing.
        """
        return self.schedule_list

espn_instance property

PYESPN: the espn client instance associated with the class

weeks property

list[Week]: a list of Week objects

__init__(espn_instance, schedule_list, load_odds=False, load_plays=False)

Initializes the Schedule instance.

Parameters:

Name Type Description Default
espn_instance PYESPN

The ESPN API wrapper instance.

required
schedule_list list[str]

A list of URLs pointing to weekly or daily schedule endpoints.

required
Source code in pyespn/classes/schedule.py
def __init__(self, espn_instance, schedule_list: list,
             load_odds: bool = False,
             load_plays: bool = False):
    """
    Initializes the Schedule instance.

    Args:
        espn_instance (PYESPN): The ESPN API wrapper instance.
        schedule_list (list[str]): A list of URLs pointing to weekly or daily schedule endpoints.
    """
    self.schedule_list = schedule_list
    self._espn_instance = espn_instance
    self.load_odds = load_odds
    self.load_plays = load_plays
    self.api_info = self._espn_instance.api_mapping

    self.season = get_an_id(self.schedule_list[0], 'seasons')
    self.schedule_type = None
    self._weeks = []

    schedule_type_id = get_schedule_type(self.schedule_list[0])

    if schedule_type_id == 1:
        self.schedule_type = 'pre'
    elif schedule_type_id == 2:
        self.schedule_type = 'regular'
    elif schedule_type_id == 3:
        self.schedule_type = 'post'

    if self.api_info.get('schedule') == 'weekly':
        self._set_schedule_weekly_data()
    elif self.api_info.get('schedule') == 'daily':
        self._set_schedule_daily_data()
    else:
        raise ScheduleTypeUnknownError(league_abbv=self._espn_instance.league_abbv)

__repr__()

Returns a string representation of the schedule instance.

Returns:

Name Type Description
str str

A formatted string with the schedule.

Source code in pyespn/classes/schedule.py
def __repr__(self) -> str:
    """
    Returns a string representation of the schedule instance.

    Returns:
        str: A formatted string with the schedule.
    """
    return f"<Schedule | {self.season} {self.schedule_type} season>"

get_events(week_num)

Retrieves the list of events for the specified week.

Parameters:

Name Type Description Default
week_num int

The week number to retrieve events for.

required

Returns:

Type Description
list[Event]

list[Event]: A list of Event instances representing the scheduled games for the specified week.

Raises:

Type Description
StopIteration

If no Week instance is found for the specified week number.

Source code in pyespn/classes/schedule.py
def get_events(self, week_num: int) -> list["Event"]:
    """
    Retrieves the list of events for the specified week.

    Args:
        week_num (int): The week number to retrieve events for.

    Returns:
        list[Event]: A list of Event instances representing the scheduled games for the specified week.

    Raises:
        StopIteration: If no Week instance is found for the specified week number.
    """
    week = next((week for week in self._weeks if str(week.week_number) == str(week_num)), None)

    if week is None:
        raise ValueError(f"No events found for week number {week_num}")

    return week.events

to_dict()

Converts the Schedule instance to its original list of JSON dictionaries.

Returns:

Name Type Description
list list

A list of dictionaries, each representing a scheduled event or game.

Note

This method returns the raw schedule data as a list of dictionaries, suitable for serialization or further processing.

Source code in pyespn/classes/schedule.py
def to_dict(self) -> list:
    """
    Converts the Schedule instance to its original list of JSON dictionaries.

    Returns:
        list: A list of dictionaries, each representing a scheduled event or game.

    Note:
        This method returns the raw schedule data as a list of dictionaries,
        suitable for serialization or further processing.
    """
    return self.schedule_list