79376110

Date: 2025-01-21 22:42:32
Score: 0.5
Natty:
Report link

I used the ClassVar type cast then created a reset class method to reset the counter if there are multiple games being scraped so it doesn't keep incrementing to n plays.

import requests
from pydantic import BaseModel
from typing import List, ClassVar

url = "https://statsapi.mlb.com/api/v1.1/game/745707/feed/live/diffPatch"
response = requests.get(url).json()

class AtBat(BaseModel):
   ab_number: int = None 
   _counter: ClassVar[int] = 1
   
   def __init__(self, **data):
       super().__init__(**data)
       self.ab_number = AtBat._counter
       AtBat._counter += 1
    
   @classmethod 
   def reset_count(cls):
        cls._counter = 1

class Plays(BaseModel):
   allPlays: List[AtBat]

   def __init__(self, **data):
       super().__init__(**data)
       AtBat.reset_count()

data = Plays(**response['liveData']['plays'])
print(data)

Appreciate the help.

Reasons:
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Self-answer (0.5):
  • Low reputation (1):
Posted by: Newman