diff --git a/pybaseball/teamid_lookup.py b/pybaseball/teamid_lookup.py index 07bcba97..c41d8981 100644 --- a/pybaseball/teamid_lookup.py +++ b/pybaseball/teamid_lookup.py @@ -24,6 +24,16 @@ def team_ids(season: Optional[int] = None, league: str = 'ALL') -> pd.DataFrame: fg_team_data = pd.read_csv(_DATA_FILENAME, index_col=0) + max_year = int(fg_team_data['yearID'].max()) + + # If the requested season is beyond the data, extrapolate from the last known year. + # MLB team composition hasn't changed since 2021 (when the bundled data ends), + # so it's safe to reuse the last year's data for recent seasons. + if season is not None and season > max_year: + last_year_data = fg_team_data[fg_team_data['yearID'] == max_year].copy() + last_year_data['yearID'] = season + fg_team_data = pd.concat([fg_team_data, last_year_data], ignore_index=True) + if season is not None: fg_team_data = fg_team_data.query(f"yearID == {season}") diff --git a/tests/pybaseball/test_teamid_lookup.py b/tests/pybaseball/test_teamid_lookup.py index 87d05e00..209b3d37 100644 --- a/tests/pybaseball/test_teamid_lookup.py +++ b/tests/pybaseball/test_teamid_lookup.py @@ -141,3 +141,21 @@ def test_get_close_team_matches() -> None: for _, row in lahman_teams.iterrows(): assert _get_close_team_matches(row, fg_teams) == row.expected + + +def test_team_id_lookup_recent_season() -> None: + # Regression test for #486: seasons after the bundled data's final year + # previously returned an empty DataFrame. team_ids should now extrapolate + # from the most recent known year, since MLB team composition is unchanged. + from pybaseball.teamid_lookup import _DATA_FILENAME + + max_year = int(pd.read_csv(_DATA_FILENAME, index_col=0)['yearID'].max()) + recent_season = max_year + 2 + + result = team_ids(recent_season) + + assert result is not None + assert not result.empty + assert len(result.columns) == 7 + assert len(result) == 30 + assert (result['yearID'] == recent_season).all()