Skip to content

Team Class

Represents a sports team within the ESPN API framework.

This class stores team-related information and maintains a reference to a PYESPN instance, allowing access to league-specific details.

Attributes:

Name Type Description
espn_instance PYESPN

The parent PYESPN instance providing access to league details.

team_json dict

The raw team data retrieved from the ESPN API.

team_id str | None

The unique identifier for the team.

guid str | None

The GUID associated with the team.

uid str | None

The UID of the team.

location str | None

The geographical location or city of the team.

name str | None

The official name of the team.

nickname str | None

The team's nickname.

abbreviation str | None

The team's short abbreviation (e.g., 'NYG', 'LAL').

display_name str | None

The full display name of the team.

short_display_name str | None

A shorter version of the display name.

primary_color str | None

The team's primary color (hex code).

alternate_color str | None

The team's alternate color (hex code).

is_active bool | None

Indicates whether the team is currently active.

is_all_star bool | None

Indicates if the team is an all-star team.

logos list[str]

A list of URLs to the team’s logos.

venue_json dict

The raw venue data associated with the team.

home_venue Venue

The Venue instance representing the team's home venue.

links dict

A dictionary mapping link types (e.g., 'official site') to their URLs.

Methods:

Name Description
get_logo_img

Returns the list of team logo URLs.

get_team_colors

Returns the team's primary and alternate colors.

get_home_venue

Retrieves the home venue of the team as a Venue instance.

get_league

Retrieves the league abbreviation associated with the team.

to_dict

Returns the raw team JSON data as a dictionary.

get_player_by_season_id

Finds and returns the Player object that matches the given player_id for a specific season.

__repr__

Returns a string representation of the Team instance.

_load_team_data

Extracts and sets the team data from the provided JSON.

load_team_season_stats

Fetches and loads team-level statistical data for a specific season using concurrent requests.

load_season_roster

Loads the team roster for a given season, using concurrent API requests to fetch player data.

load_season_results

Retrieves and stores seasonal game records for the team.

load_season_coaches

Loads the coaching staff for the team in the specified season.

load_season_betting_records

Fetches and loads the betting odds records for a specific team and season using concurrent requests.

Source code in pyespn/classes/team.py
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
@validate_json("team_json")
class Team:
    """
    Represents a sports team within the ESPN API framework.

    This class stores team-related information and maintains a reference
    to a `PYESPN` instance, allowing access to league-specific details.

    Attributes:
        espn_instance (PYESPN): The parent `PYESPN` instance providing access to league details.
        team_json (dict): The raw team data retrieved from the ESPN API.
        team_id (str | None): The unique identifier for the team.
        guid (str | None): The GUID associated with the team.
        uid (str | None): The UID of the team.
        location (str | None): The geographical location or city of the team.
        name (str | None): The official name of the team.
        nickname (str | None): The team's nickname.
        abbreviation (str | None): The team's short abbreviation (e.g., 'NYG', 'LAL').
        display_name (str | None): The full display name of the team.
        short_display_name (str | None): A shorter version of the display name.
        primary_color (str | None): The team's primary color (hex code).
        alternate_color (str | None): The team's alternate color (hex code).
        is_active (bool | None): Indicates whether the team is currently active.
        is_all_star (bool | None): Indicates if the team is an all-star team.
        logos (list[str]): A list of URLs to the team’s logos.
        venue_json (dict): The raw venue data associated with the team.
        home_venue (Venue): The `Venue` instance representing the team's home venue.
        links (dict): A dictionary mapping link types (e.g., 'official site') to their URLs.

    Methods:
        get_logo_img() -> list[str]:
            Returns the list of team logo URLs.

        get_team_colors() -> dict:
            Returns the team's primary and alternate colors.

        get_home_venue() -> Venue:
            Retrieves the home venue of the team as a `Venue` instance.

        get_league() -> str:
            Retrieves the league abbreviation associated with the team.

        to_dict() -> dict:
            Returns the raw team JSON data as a dictionary.

        get_player_by_season_id(season, player_id) -> Player:
            Finds and returns the Player object that matches the given player_id for a specific season.

        __repr__() -> str:
            Returns a string representation of the Team instance.

        _load_team_data() -> None:
            Extracts and sets the team data from the provided JSON.

        load_team_season_stats(season) -> None:
            Fetches and loads team-level statistical data for a specific season using concurrent requests.

        load_season_roster(season) -> None:
            Loads the team roster for a given season, using concurrent API requests to fetch player data.

        load_season_results(season) -> None:
            Retrieves and stores seasonal game records for the team.

        load_season_coaches(season) -> None:
            Loads the coaching staff for the team in the specified season.

        load_season_betting_records(season) -> None:
            Fetches and loads the betting odds records for a specific team and season using concurrent requests.
    """

    def __init__(self, espn_instance, team_json):
        """
        Initializes a Team instance.

        Args:
            espn_instance (PYESPN): The parent `PYESPN` instance, providing access to league details.
            team_json (dict): The raw team data retrieved from the ESPN API.

        """
        self._espn_instance = espn_instance
        self.api_info = self.espn_instance.api_mapping
        self._records = {}
        self._stats = {}
        self._coaches = {}
        self._betting = {}
        if team_json:
            self.team_json = team_json
        else:
            self.team_json = {}
        self._roster = {}
        self._load_team_data()
        self.home_venue = Venue(venue_json=self.venue_json,
                                espn_instance=self.espn_instance)

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

    @property
    def coaches(self):
        """
             dict: a dict with season as the key and a list of Player objects
        """
        return self._coaches

    @property
    def stats(self):
        """
             dict: a dict with season as the key and a list of Stat objects
        """
        return self._stats

    @property
    def records(self):
        """
             dict: a dict with season as the key and a list of Record objects
        """
        return self._records

    @property
    def betting(self):
        """
             dict: a dict with season as the key and a list of Record objects
        """
        return self._betting

    @property
    def roster(self):
        """
            dict: with season as a key and a list of Player objects
        """
        return self._roster

    @property
    def team_id(self):
        """
            str: the id for the team
        """
        return self._team_id

    def get_player_by_season_id(self, season, player_id) -> "Player":
        """
        Finds and returns the Team object that matches the given team_id.

        Args:
            season (int or str): the season to pull the athlete from
            player_id (int or str): The ID of the player to find.

        Returns:
            Player: The matching Team object, or None if not found.
        """
        return next((player for player in self._roster.get(season, []) if str(player.id) == str(player_id)), None)

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

        Returns:
            str: A formatted string with the team's location, name, abbreviation, and league.
        """
        return f"<Team | {self.location} {self.name} ({self.abbreviation}) - {self.get_league()}>"

    def load_season_roster_box_score(self, season):

        for player in self._roster.get(season, []):
            player.load_player_box_scores_season(season=season)

    def _load_team_data(self):
        """
        Extracts and sets team data from the provided JSON.
        """
        self.ref = self.team_json.get('$ref')
        self._team_id = self.team_json.get("id")
        self.guid = self.team_json.get("guid")
        self.uid = self.team_json.get("uid")
        self.location = self.team_json.get("location")
        self.name = self.team_json.get("name")
        self.nickname = self.team_json.get("nickname")
        self.abbreviation = self.team_json.get("abbreviation")
        self.display_name = self.team_json.get("displayName")
        self.short_display_name = self.team_json.get("shortDisplayName")
        self.primary_color = self.team_json.get("color")
        self.alternate_color = self.team_json.get("alternateColor")
        self.is_active = self.team_json.get("isActive")
        self.is_all_star = self.team_json.get("isAllStar")

        self.logos = [Image(image_json=logo, espn_instance=self.espn_instance) for logo in self.team_json.get("logos", [])]
        self.venue_json = self.team_json.get("venue", {})

        self.links = {link["rel"][0]: link["href"] for link in self.team_json.get("links", []) if "rel" in link}

    def load_team_season_stats(self, season):
        """
        Fetches and loads team-level statistical data for a specific season, using threading to fetch multiple pages concurrently.

        This method sends a request to the ESPN API to retrieve team statistics for the given season. It will send requests for
        multiple pages of data if necessary, and each page is fetched concurrently using a thread pool. The method parses the
        response and instantiates `Stat` objects for each statistic found under the `categories` section of the response.
        All parsed statistics are then stored in the `self._stats` dictionary, keyed by the provided season.

        Args:
            season (int): The season year for which statistics should be retrieved.

        Raises:
            API400Error: If the API responds with a 400-level error. A message is printed, and no data is stored for the season.
        """
        url = f'http://sports.core.api.espn.com/{self.espn_instance.v}/sports/{self.api_info["sport"]}/leagues/{self.api_info["league"]}/seasons/{season}/types/2/teams/{self._team_id}/statistics'

        all_stats = []
        try:
            stats_content = fetch_espn_data(url)
            pages = stats_content.get('pageCount', 0)

            # Using ThreadPoolExecutor to fetch multiple pages concurrently
            with ThreadPoolExecutor() as executor:
                future_to_page = {
                    executor.submit(fetch_espn_data, f'{url}?page={page}'): page
                    for page in range(1, pages + 1)
                }

                # Collect results as they complete
                for future in as_completed(future_to_page):
                    page_data = future.result()
                    for categories in page_data.get('splits', {}).get('categories', []):
                        for stat in categories.get('stats', []):
                            all_stats.append(Stat(stat_json=stat,
                                                  espn_instance=self.espn_instance))

        except API400Error as e:
            print(f"Failed to fetch stats data for season {season} | team {self.name} | id {self._team_id}: {e}")

        # Store the fetched stats data
        self._stats[season] = all_stats

    def get_team_colors(self) -> dict:
        """
        Retrieves the team's primary and alternate colors.

        Returns:
            dict: A dictionary containing 'primary_color' and 'alt_color' keys with their respective hex values.
        """
        return {
            'primary_color': self.primary_color,
            'alt_color': self.alternate_color
        }

    def get_home_venue(self) -> Venue:
        """
        Retrieves the home venue of the team.

        Returns:
            Venue: The `Venue` instance representing the team's home venue.
        """
        return self.home_venue

    def get_league(self) -> str:
        """
        Retrieves the league abbreviation from the associated `PYESPN` instance.

        Returns:
            str: The league abbreviation (e.g., 'nfl', 'nba', 'cfb').
        """
        return self.espn_instance.league_abbv

    def load_season_roster(self, season) -> None:
        """
        Loads the team roster for a given season using ESPN API data.

        This function retrieves the roster for the specified season by:
        - Fetching paginated lists of athletes.
        - Concurrently retrieving detailed athlete data using multiple API requests.
        - Storing the roster data in the `self._roster` dictionary.

        Args:
            season (int): The season year for which to load the roster.

        Returns:
            None: The function updates `self._roster` with the retrieved players.

        Raises:
            Exception: Logs any errors encountered when fetching player data.

        Example:
            >>> team.load_season_roster(2023)
            >>> print(team.roster[2023])
            [<Player | John Doe>, <Player | Jane Smith>, ...]

        Note:
            - Uses `ThreadPoolExecutor` for concurrent fetching of athlete data to improve performance.
            - The number of worker threads (`max_workers=10`) can be adjusted based on API rate limits.
        """

        url = f'http://sports.core.api.espn.com/{self.espn_instance.v}/sports/{self.api_info.get("sport")}/leagues/{self.api_info.get("league")}/seasons/{season}/teams/{self._team_id}/athletes'
        content = fetch_espn_data(url)
        page_count = content.get('pageCount', 1)

        athletes = []
        athlete_urls = []

        # Collect all athlete URLs first
        for page in range(1, page_count + 1):
            page_url = f'{url}?page={page}'
            page_content = fetch_espn_data(page_url)
            for athlete in page_content.get('items', []):
                athlete_urls.append(athlete.get('$ref'))

        # Fetch athlete data in parallel
        with ThreadPoolExecutor(max_workers=10) as executor:  # Adjust workers as needed
            future_to_url = {executor.submit(fetch_espn_data, url): url for url in athlete_urls}

            for future in as_completed(future_to_url):
                try:
                    athlete_content = future.result()
                    athletes.append(Player(player_json=athlete_content, espn_instance=self.espn_instance))
                except Exception as e:
                    print(f"Failed to fetch athlete data: {e}")

        self._roster[season] = athletes

    def load_season_results(self, season):
        """
        Retrieves and stores seasonal game records for the team.

        This method constructs a URL to the ESPN API using the team’s league and sport information,
        then fetches and parses the game results (win/loss record) for the specified season.
        Each result is wrapped in a `Record` object, which is stored in the team's `records`
        dictionary under the given season key.

        Args:
            season (int): The season year for which the team’s game records should be retrieved.

        Side Effects:
            Updates the `self._records` dictionary with a list of `Record` instances representing
            seasonal game results.

        """
        url = f'http://sports.core.api.espn.com/{self.espn_instance.v}/sports/{self.api_info["sport"]}/leagues/{self.api_info["league"]}/seasons/{season}/types/2/teams/{self._team_id}/record?lang=en&region=us'
        season_records = []

        try:
            with ThreadPoolExecutor(max_workers=1) as executor:
                future = executor.submit(fetch_espn_data, url)
                results_content = future.result(timeout=10)  # timeout in seconds

                for result in results_content.get('items', []):
                    season_records.append(Record(record_json=result,
                                                 espn_instance=self.espn_instance))

            self._records[season] = season_records

        except TimeoutError:
            print(f"Timeout while fetching season records for season {season} | team {self.name} | id {self._team_id}")
        except API400Error as e:
            print(f"API error while fetching season records for season {season} | team {self.name} | id {self._team_id}: {e}")
        except Exception as e:
            print(f"Unexpected error while fetching season records for season {season} | team {self.name} | id {self._team_id}: {e}")

    def load_season_coaches(self, season):
        """
        Loads the coaching staff for the team in the specified season.

        This method retrieves a list of coach references for the team from the ESPN API,
        then performs follow-up requests to fetch detailed information for each coach.
        Each coach is instantiated as a `Player` object (representing coaching personnel)
        and added to the `coaches` dictionary under the corresponding season.

        Args:
            season (int): The season year for which coaching data should be loaded.

        Side Effects:
            Updates the `self._coaches` dictionary with a list of `Player` instances
            representing the coaching staff.

        Notes:
            Coach data is retrieved in two stages: first a summary list with URLs,
            then a second pass to fetch detailed info for each coach using those URLs.
        """
        url = f'http://sports.core.api.espn.com/{self.espn_instance.v}/sports/{self.api_info["sport"]}/leagues/{self.api_info["league"]}/seasons/{season}/teams/{self._team_id}/coaches?lang=en&region=us'
        coach_content = fetch_espn_data(url)
        coach_records = []
        coach_urls = []
        for coach in coach_content.get('items', []):
            coach_urls.append(coach.get('$ref'))

        for coach_url in coach_urls:
            coach_url_response = fetch_espn_data(coach_url)
            coach_records.append(Player(player_json=coach_url_response,
                                        espn_instance=self.espn_instance))

        self._coaches[season] = coach_records

    def load_season_betting_records(self, season):
        """
        Fetches and loads the betting odds records for a specific team and season using concurrent requests.

        This method queries the ESPN API for team-specific betting records for the given season. It handles
        pagination and leverages a thread pool to fetch data pages concurrently, improving performance. The
        fetched data is parsed into `Record` instances and stored in the `self._espn_instance` dictionary under
        the specified season.

        Args:
            season (int): The season year to fetch betting odds records for.

        Raises:
            API400Error: If the ESPN API returns a 400 error (e.g., invalid season or unavailable data).
        """
        futures = []
        url = f'http://sports.core.api.espn.com/{self.espn_instance.v}/sports/{self.api_info["sport"]}/leagues/{self.api_info["league"]}/seasons/{season}/types/0/teams/{self._team_id}/odds-records'

        try:
            season_content = fetch_espn_data(url)
            pages = season_content.get('pageCount', 0)

            with ThreadPoolExecutor() as executor:
                future_to_page = {
                    executor.submit(fetch_espn_data, f'{url}?page={page}'): page
                    for page in range(1, pages + 1)
                }

                for future in as_completed(future_to_page):
                    page_data = future.result()
                    for bet in page_data.get('items', []):
                        futures.append(Record(record_json=bet,
                                              espn_instance=self.espn_instance))

            self._betting[season] = futures

        except API400Error as e:
            print(f"Failed to fetch oddsbetting data for season {season} | team {self.name} | id {self._team_id}: {e}")

    def to_dict(self) -> dict:
        """
        Returns the raw team JSON data as a dictionary.

        Returns:
            dict: The original team data retrieved from the ESPN API.
        """
        return self.team_json

betting property

dict: a dict with season as the key and a list of Record objects

coaches property

dict: a dict with season as the key and a list of Player objects

espn_instance property

PYESPN: the espn client instance associated with the class

records property

dict: a dict with season as the key and a list of Record objects

roster property

dict: with season as a key and a list of Player objects

stats property

dict: a dict with season as the key and a list of Stat objects

team_id property

str: the id for the team

__init__(espn_instance, team_json)

Initializes a Team instance.

Parameters:

Name Type Description Default
espn_instance PYESPN

The parent PYESPN instance, providing access to league details.

required
team_json dict

The raw team data retrieved from the ESPN API.

required
Source code in pyespn/classes/team.py
def __init__(self, espn_instance, team_json):
    """
    Initializes a Team instance.

    Args:
        espn_instance (PYESPN): The parent `PYESPN` instance, providing access to league details.
        team_json (dict): The raw team data retrieved from the ESPN API.

    """
    self._espn_instance = espn_instance
    self.api_info = self.espn_instance.api_mapping
    self._records = {}
    self._stats = {}
    self._coaches = {}
    self._betting = {}
    if team_json:
        self.team_json = team_json
    else:
        self.team_json = {}
    self._roster = {}
    self._load_team_data()
    self.home_venue = Venue(venue_json=self.venue_json,
                            espn_instance=self.espn_instance)

__repr__()

Returns a string representation of the Team instance.

Returns:

Name Type Description
str str

A formatted string with the team's location, name, abbreviation, and league.

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

    Returns:
        str: A formatted string with the team's location, name, abbreviation, and league.
    """
    return f"<Team | {self.location} {self.name} ({self.abbreviation}) - {self.get_league()}>"

get_home_venue()

Retrieves the home venue of the team.

Returns:

Name Type Description
Venue Venue

The Venue instance representing the team's home venue.

Source code in pyespn/classes/team.py
def get_home_venue(self) -> Venue:
    """
    Retrieves the home venue of the team.

    Returns:
        Venue: The `Venue` instance representing the team's home venue.
    """
    return self.home_venue

get_league()

Retrieves the league abbreviation from the associated PYESPN instance.

Returns:

Name Type Description
str str

The league abbreviation (e.g., 'nfl', 'nba', 'cfb').

Source code in pyespn/classes/team.py
def get_league(self) -> str:
    """
    Retrieves the league abbreviation from the associated `PYESPN` instance.

    Returns:
        str: The league abbreviation (e.g., 'nfl', 'nba', 'cfb').
    """
    return self.espn_instance.league_abbv

get_player_by_season_id(season, player_id)

Finds and returns the Team object that matches the given team_id.

Parameters:

Name Type Description Default
season int or str

the season to pull the athlete from

required
player_id int or str

The ID of the player to find.

required

Returns:

Name Type Description
Player Player

The matching Team object, or None if not found.

Source code in pyespn/classes/team.py
def get_player_by_season_id(self, season, player_id) -> "Player":
    """
    Finds and returns the Team object that matches the given team_id.

    Args:
        season (int or str): the season to pull the athlete from
        player_id (int or str): The ID of the player to find.

    Returns:
        Player: The matching Team object, or None if not found.
    """
    return next((player for player in self._roster.get(season, []) if str(player.id) == str(player_id)), None)

get_team_colors()

Retrieves the team's primary and alternate colors.

Returns:

Name Type Description
dict dict

A dictionary containing 'primary_color' and 'alt_color' keys with their respective hex values.

Source code in pyespn/classes/team.py
def get_team_colors(self) -> dict:
    """
    Retrieves the team's primary and alternate colors.

    Returns:
        dict: A dictionary containing 'primary_color' and 'alt_color' keys with their respective hex values.
    """
    return {
        'primary_color': self.primary_color,
        'alt_color': self.alternate_color
    }

load_season_betting_records(season)

Fetches and loads the betting odds records for a specific team and season using concurrent requests.

This method queries the ESPN API for team-specific betting records for the given season. It handles pagination and leverages a thread pool to fetch data pages concurrently, improving performance. The fetched data is parsed into Record instances and stored in the self._espn_instance dictionary under the specified season.

Parameters:

Name Type Description Default
season int

The season year to fetch betting odds records for.

required

Raises:

Type Description
API400Error

If the ESPN API returns a 400 error (e.g., invalid season or unavailable data).

Source code in pyespn/classes/team.py
def load_season_betting_records(self, season):
    """
    Fetches and loads the betting odds records for a specific team and season using concurrent requests.

    This method queries the ESPN API for team-specific betting records for the given season. It handles
    pagination and leverages a thread pool to fetch data pages concurrently, improving performance. The
    fetched data is parsed into `Record` instances and stored in the `self._espn_instance` dictionary under
    the specified season.

    Args:
        season (int): The season year to fetch betting odds records for.

    Raises:
        API400Error: If the ESPN API returns a 400 error (e.g., invalid season or unavailable data).
    """
    futures = []
    url = f'http://sports.core.api.espn.com/{self.espn_instance.v}/sports/{self.api_info["sport"]}/leagues/{self.api_info["league"]}/seasons/{season}/types/0/teams/{self._team_id}/odds-records'

    try:
        season_content = fetch_espn_data(url)
        pages = season_content.get('pageCount', 0)

        with ThreadPoolExecutor() as executor:
            future_to_page = {
                executor.submit(fetch_espn_data, f'{url}?page={page}'): page
                for page in range(1, pages + 1)
            }

            for future in as_completed(future_to_page):
                page_data = future.result()
                for bet in page_data.get('items', []):
                    futures.append(Record(record_json=bet,
                                          espn_instance=self.espn_instance))

        self._betting[season] = futures

    except API400Error as e:
        print(f"Failed to fetch oddsbetting data for season {season} | team {self.name} | id {self._team_id}: {e}")

load_season_coaches(season)

Loads the coaching staff for the team in the specified season.

This method retrieves a list of coach references for the team from the ESPN API, then performs follow-up requests to fetch detailed information for each coach. Each coach is instantiated as a Player object (representing coaching personnel) and added to the coaches dictionary under the corresponding season.

Parameters:

Name Type Description Default
season int

The season year for which coaching data should be loaded.

required
Side Effects

Updates the self._coaches dictionary with a list of Player instances representing the coaching staff.

Notes

Coach data is retrieved in two stages: first a summary list with URLs, then a second pass to fetch detailed info for each coach using those URLs.

Source code in pyespn/classes/team.py
def load_season_coaches(self, season):
    """
    Loads the coaching staff for the team in the specified season.

    This method retrieves a list of coach references for the team from the ESPN API,
    then performs follow-up requests to fetch detailed information for each coach.
    Each coach is instantiated as a `Player` object (representing coaching personnel)
    and added to the `coaches` dictionary under the corresponding season.

    Args:
        season (int): The season year for which coaching data should be loaded.

    Side Effects:
        Updates the `self._coaches` dictionary with a list of `Player` instances
        representing the coaching staff.

    Notes:
        Coach data is retrieved in two stages: first a summary list with URLs,
        then a second pass to fetch detailed info for each coach using those URLs.
    """
    url = f'http://sports.core.api.espn.com/{self.espn_instance.v}/sports/{self.api_info["sport"]}/leagues/{self.api_info["league"]}/seasons/{season}/teams/{self._team_id}/coaches?lang=en&region=us'
    coach_content = fetch_espn_data(url)
    coach_records = []
    coach_urls = []
    for coach in coach_content.get('items', []):
        coach_urls.append(coach.get('$ref'))

    for coach_url in coach_urls:
        coach_url_response = fetch_espn_data(coach_url)
        coach_records.append(Player(player_json=coach_url_response,
                                    espn_instance=self.espn_instance))

    self._coaches[season] = coach_records

load_season_results(season)

Retrieves and stores seasonal game records for the team.

This method constructs a URL to the ESPN API using the team’s league and sport information, then fetches and parses the game results (win/loss record) for the specified season. Each result is wrapped in a Record object, which is stored in the team's records dictionary under the given season key.

Parameters:

Name Type Description Default
season int

The season year for which the team’s game records should be retrieved.

required
Side Effects

Updates the self._records dictionary with a list of Record instances representing seasonal game results.

Source code in pyespn/classes/team.py
def load_season_results(self, season):
    """
    Retrieves and stores seasonal game records for the team.

    This method constructs a URL to the ESPN API using the team’s league and sport information,
    then fetches and parses the game results (win/loss record) for the specified season.
    Each result is wrapped in a `Record` object, which is stored in the team's `records`
    dictionary under the given season key.

    Args:
        season (int): The season year for which the team’s game records should be retrieved.

    Side Effects:
        Updates the `self._records` dictionary with a list of `Record` instances representing
        seasonal game results.

    """
    url = f'http://sports.core.api.espn.com/{self.espn_instance.v}/sports/{self.api_info["sport"]}/leagues/{self.api_info["league"]}/seasons/{season}/types/2/teams/{self._team_id}/record?lang=en&region=us'
    season_records = []

    try:
        with ThreadPoolExecutor(max_workers=1) as executor:
            future = executor.submit(fetch_espn_data, url)
            results_content = future.result(timeout=10)  # timeout in seconds

            for result in results_content.get('items', []):
                season_records.append(Record(record_json=result,
                                             espn_instance=self.espn_instance))

        self._records[season] = season_records

    except TimeoutError:
        print(f"Timeout while fetching season records for season {season} | team {self.name} | id {self._team_id}")
    except API400Error as e:
        print(f"API error while fetching season records for season {season} | team {self.name} | id {self._team_id}: {e}")
    except Exception as e:
        print(f"Unexpected error while fetching season records for season {season} | team {self.name} | id {self._team_id}: {e}")

load_season_roster(season)

Loads the team roster for a given season using ESPN API data.

This function retrieves the roster for the specified season by: - Fetching paginated lists of athletes. - Concurrently retrieving detailed athlete data using multiple API requests. - Storing the roster data in the self._roster dictionary.

Parameters:

Name Type Description Default
season int

The season year for which to load the roster.

required

Returns:

Name Type Description
None None

The function updates self._roster with the retrieved players.

Raises:

Type Description
Exception

Logs any errors encountered when fetching player data.

Example

team.load_season_roster(2023) print(team.roster[2023]) [, , ...]

Note
  • Uses ThreadPoolExecutor for concurrent fetching of athlete data to improve performance.
  • The number of worker threads (max_workers=10) can be adjusted based on API rate limits.
Source code in pyespn/classes/team.py
def load_season_roster(self, season) -> None:
    """
    Loads the team roster for a given season using ESPN API data.

    This function retrieves the roster for the specified season by:
    - Fetching paginated lists of athletes.
    - Concurrently retrieving detailed athlete data using multiple API requests.
    - Storing the roster data in the `self._roster` dictionary.

    Args:
        season (int): The season year for which to load the roster.

    Returns:
        None: The function updates `self._roster` with the retrieved players.

    Raises:
        Exception: Logs any errors encountered when fetching player data.

    Example:
        >>> team.load_season_roster(2023)
        >>> print(team.roster[2023])
        [<Player | John Doe>, <Player | Jane Smith>, ...]

    Note:
        - Uses `ThreadPoolExecutor` for concurrent fetching of athlete data to improve performance.
        - The number of worker threads (`max_workers=10`) can be adjusted based on API rate limits.
    """

    url = f'http://sports.core.api.espn.com/{self.espn_instance.v}/sports/{self.api_info.get("sport")}/leagues/{self.api_info.get("league")}/seasons/{season}/teams/{self._team_id}/athletes'
    content = fetch_espn_data(url)
    page_count = content.get('pageCount', 1)

    athletes = []
    athlete_urls = []

    # Collect all athlete URLs first
    for page in range(1, page_count + 1):
        page_url = f'{url}?page={page}'
        page_content = fetch_espn_data(page_url)
        for athlete in page_content.get('items', []):
            athlete_urls.append(athlete.get('$ref'))

    # Fetch athlete data in parallel
    with ThreadPoolExecutor(max_workers=10) as executor:  # Adjust workers as needed
        future_to_url = {executor.submit(fetch_espn_data, url): url for url in athlete_urls}

        for future in as_completed(future_to_url):
            try:
                athlete_content = future.result()
                athletes.append(Player(player_json=athlete_content, espn_instance=self.espn_instance))
            except Exception as e:
                print(f"Failed to fetch athlete data: {e}")

    self._roster[season] = athletes

load_team_season_stats(season)

Fetches and loads team-level statistical data for a specific season, using threading to fetch multiple pages concurrently.

This method sends a request to the ESPN API to retrieve team statistics for the given season. It will send requests for multiple pages of data if necessary, and each page is fetched concurrently using a thread pool. The method parses the response and instantiates Stat objects for each statistic found under the categories section of the response. All parsed statistics are then stored in the self._stats dictionary, keyed by the provided season.

Parameters:

Name Type Description Default
season int

The season year for which statistics should be retrieved.

required

Raises:

Type Description
API400Error

If the API responds with a 400-level error. A message is printed, and no data is stored for the season.

Source code in pyespn/classes/team.py
def load_team_season_stats(self, season):
    """
    Fetches and loads team-level statistical data for a specific season, using threading to fetch multiple pages concurrently.

    This method sends a request to the ESPN API to retrieve team statistics for the given season. It will send requests for
    multiple pages of data if necessary, and each page is fetched concurrently using a thread pool. The method parses the
    response and instantiates `Stat` objects for each statistic found under the `categories` section of the response.
    All parsed statistics are then stored in the `self._stats` dictionary, keyed by the provided season.

    Args:
        season (int): The season year for which statistics should be retrieved.

    Raises:
        API400Error: If the API responds with a 400-level error. A message is printed, and no data is stored for the season.
    """
    url = f'http://sports.core.api.espn.com/{self.espn_instance.v}/sports/{self.api_info["sport"]}/leagues/{self.api_info["league"]}/seasons/{season}/types/2/teams/{self._team_id}/statistics'

    all_stats = []
    try:
        stats_content = fetch_espn_data(url)
        pages = stats_content.get('pageCount', 0)

        # Using ThreadPoolExecutor to fetch multiple pages concurrently
        with ThreadPoolExecutor() as executor:
            future_to_page = {
                executor.submit(fetch_espn_data, f'{url}?page={page}'): page
                for page in range(1, pages + 1)
            }

            # Collect results as they complete
            for future in as_completed(future_to_page):
                page_data = future.result()
                for categories in page_data.get('splits', {}).get('categories', []):
                    for stat in categories.get('stats', []):
                        all_stats.append(Stat(stat_json=stat,
                                              espn_instance=self.espn_instance))

    except API400Error as e:
        print(f"Failed to fetch stats data for season {season} | team {self.name} | id {self._team_id}: {e}")

    # Store the fetched stats data
    self._stats[season] = all_stats

to_dict()

Returns the raw team JSON data as a dictionary.

Returns:

Name Type Description
dict dict

The original team data retrieved from the ESPN API.

Source code in pyespn/classes/team.py
def to_dict(self) -> dict:
    """
    Returns the raw team JSON data as a dictionary.

    Returns:
        dict: The original team data retrieved from the ESPN API.
    """
    return self.team_json