toddrob99 / MLB-StatsAPI

Python wrapper for MLB Stats API
GNU General Public License v3.0
513 stars 98 forks source link

Unexpected behavior in lookup_player() when season is not specified #127

Closed enjoymoreradio closed 9 months ago

enjoymoreradio commented 10 months ago

Related to this discussion in the subreddit. When a season parameter is not specified when calling lookup_player, the function calls latest_season() as a fallback.

def lookup_player(lookup_value, gameType=None, season=None, sportId=1):
...
    if not season:
        season_data = latest_season(sportId=sportId)
        season = season_data.get("seasonId", datetime.now().year)
    params.update(
        {
            "season": season,
        }
...

latest_season() makes a request to the API for a list of all seasons, and returns the last item in the list

def latest_season(sportId=1):
    """Get the latest season for a given sportId. Returns a dict containing seasonId and various dates."""
    params = {
        "sportId": sportId,
        "seasonId": "all",
    }
    all_seasons = get("season", params)

    return all_seasons.get("seasons")[-1]

This works unless and until MLB adds a season that has not yet started to their database, as they recently did with 2024. The latest_season() function should return 2023 at least until the conclusion of 2023 World Series, if not later.

toddrob99 commented 9 months ago

I just tested this again and it's working for the 2024 season now. It appears the season record was created, and then later the players were associated with the new season.

Nevertheless, I am updating statsapi.latest_season() to return the current season if one is active based on seasonStartDate and seasonEndDate, otherwise the true latest season. I think this is the expected behavior. This will be in version 1.7.