Skip to content

Commit bfe8d8e

Browse files
committed
Modified comments and docstrings
1 parent a3e9251 commit bfe8d8e

File tree

1 file changed

+39
-28
lines changed

1 file changed

+39
-28
lines changed

statsapi/__init__.py

Lines changed: 39 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,19 @@
1+
"""# MLB-StatsAPI
2+
3+
Python wrapper for MLB Stats API
4+
5+
Created by Todd Roberts
6+
7+
https://pypi.org/project/MLB-StatsAPI/
8+
9+
https://github.com/toddrob99/MLB-StatsAPI
10+
"""
111
# encoding=utf-8
212
import sys
313
if sys.version_info.major < 3:
414
reload(sys)
515
sys.setdefaultencoding('utf8')
6-
"""Trying to support Python 2.7"""
16+
# Trying to support Python 2.7
717

818
from . import version
919
__version__ = version.VERSION
@@ -243,11 +253,12 @@ def boxscore(gamePk,battingBox=True,battingInfo=True,fieldingInfo=True,pitchingB
243253
For example, to retrieve only the batting box: statsapi.boxscore(565997,battingInfo=False,fieldingInfo=False,pitchingBox=False,gameInfo=False)
244254
"""
245255

246-
"""rowLen is the total width of each side of the box score, excluding the " | " separator; fullRowLen is the full table length"""
247256
rowLen = 79
257+
"""rowLen is the total width of each side of the box score, excluding the " | " separator"""
248258
fullRowLen = rowLen * 2 + 3
249-
"""boxscore will hold the string to be returned"""
259+
"""fullRowLen is the full table width"""
250260
boxscore = ''
261+
"""boxscore will hold the string to be returned"""
251262
params = {'gamePk':gamePk,'fields':'gameData,teams,teamName,shortName,teamStats,batting,atBats,runs,hits,rbi,strikeOuts,baseOnBalls,leftOnBase,pitching,inningsPitched,earnedRuns,homeRuns,players,boxscoreName,liveData,boxscore,teams,players,id,fullName,allPositions,abbreviation,seasonStats,batting,avg,ops,era,battingOrder,info,title,fieldList,note,label,value'}
252263
if timecode: params.update({'timecode':timecode})
253264
r = get('game',params)
@@ -258,7 +269,7 @@ def boxscore(gamePk,battingBox=True,battingInfo=True,fieldingInfo=True,pitchingB
258269
home = r['liveData']['boxscore']['teams']['home']
259270

260271
if battingBox:
261-
"""Add away column headers"""
272+
#Add away column headers
262273
awayBatters = [{'namefield':teamInfo['away']['teamName'] + ' Batters', 'ab':'AB', 'r':'R', 'h':'H', 'rbi':'RBI', 'bb':'BB', 'k':'K', 'lob':'LOB', 'avg':'AVG', 'ops':'OPS'}]
263274
for batterId_int in [x for x in away['batters'] if away['players']['ID'+str(x)].get('battingOrder')]:
264275
batterId = str(batterId_int)
@@ -279,7 +290,7 @@ def boxscore(gamePk,battingBox=True,battingInfo=True,fieldingInfo=True,pitchingB
279290
}
280291
awayBatters.append(batter)
281292

282-
"""Get away team totals"""
293+
#Get away team totals
283294
awayBatters.append ({
284295
'namefield':'Totals',
285296
'ab':str(away['teamStats']['batting']['atBats']),
@@ -293,7 +304,7 @@ def boxscore(gamePk,battingBox=True,battingInfo=True,fieldingInfo=True,pitchingB
293304
'ops':''
294305
})
295306

296-
"""Add home column headers"""
307+
#Add home column headers
297308
homeBatters = [{'namefield':teamInfo['home']['teamName'] + ' Batters', 'ab':'AB', 'r':'R', 'h':'H', 'rbi':'RBI', 'bb':'BB', 'k':'K', 'lob':'LOB', 'avg':'AVG', 'ops':'OPS'}]
298309
for batterId_int in [x for x in home['batters'] if home['players']['ID'+str(x)].get('battingOrder')]:
299310
batterId = str(batterId_int)
@@ -314,7 +325,7 @@ def boxscore(gamePk,battingBox=True,battingInfo=True,fieldingInfo=True,pitchingB
314325
}
315326
homeBatters.append(batter)
316327

317-
"""Get home team totals"""
328+
#Get home team totals
318329
homeBatters.append ({
319330
'namefield':'Totals',
320331
'ab':str(home['teamStats']['batting']['atBats']),
@@ -328,13 +339,13 @@ def boxscore(gamePk,battingBox=True,battingInfo=True,fieldingInfo=True,pitchingB
328339
'ops':''
329340
})
330341

331-
"""Make sure the home and away batter lists are the same length"""
342+
#Make sure the home and away batter lists are the same length
332343
while len(awayBatters) > len(homeBatters):
333344
homeBatters.append({'namefield':'','ab':'','r':'','h':'','rbi':'','bb':'','k':'','lob':'','avg':'','ops':''})
334345
while len(awayBatters) < len(homeBatters):
335346
awayBatters.append({'namefield':'','ab':'','r':'','h':'','rbi':'','bb':'','k':'','lob':'','avg':'','ops':''})
336347

337-
"""Build the batting box!"""
348+
#Build the batting box!
338349
for i in range(0,len(awayBatters)):
339350
if i==0 or i==len(awayBatters)-1:
340351
boxscore += '-'*rowLen + ' | ' + '-'*rowLen + '\n'
@@ -343,7 +354,7 @@ def boxscore(gamePk,battingBox=True,battingInfo=True,fieldingInfo=True,pitchingB
343354
if i==0 or i==len(awayBatters)-1:
344355
boxscore += '-'*rowLen + ' | ' + '-'*rowLen + '\n'
345356

346-
"""Get batting notes"""
357+
#Get batting notes
347358
awayBattingNotes = {}
348359
for n in away['note']:
349360
awayBattingNotes.update({len(awayBattingNotes) : n['label'] + '-' + n['value']})
@@ -362,7 +373,7 @@ def boxscore(gamePk,battingBox=True,battingInfo=True,fieldingInfo=True,pitchingB
362373

363374
boxscore += ' '*rowLen + ' | ' + ' '*rowLen + '\n'
364375

365-
"""Get batting and fielding info"""
376+
#Get batting and fielding info
366377
awayBoxInfo = {}
367378
homeBoxInfo = {}
368379
for infoType in ['BATTING','FIELDING']:
@@ -419,16 +430,16 @@ def boxscore(gamePk,battingBox=True,battingInfo=True,fieldingInfo=True,pitchingB
419430
while len(awayBoxInfo) < len(homeBoxInfo):
420431
awayBoxInfo.update({len(awayBoxInfo) : ''})
421432

422-
"""Build info box"""
433+
#Build info box
423434
for i in range(0,len(awayBoxInfo)):
424435
boxscore += ('{:<%s} | '%rowLen).format(awayBoxInfo[i])
425436
boxscore += ('{:<%s}\n'%rowLen).format(homeBoxInfo[i])
426437
if i==len(awayBoxInfo)-1:
427438
boxscore += '-'*rowLen + ' | ' + '-'*rowLen + '\n'
428439

429-
"""Get pitching box"""
440+
#Get pitching box
430441
if pitchingBox:
431-
"""Add away column headers"""
442+
#Add away column headers
432443
awayPitchers = [{'namefield':teamInfo['away']['teamName'] + ' Pitchers', 'ip':'IP', 'h':'H', 'r':'R', 'er':'ER', 'bb':'BB', 'k':'K', 'hr':'HR', 'era':'ERA'}]
433444
for pitcherId_int in away['pitchers']:
434445
pitcherId = str(pitcherId_int)
@@ -447,7 +458,7 @@ def boxscore(gamePk,battingBox=True,battingInfo=True,fieldingInfo=True,pitchingB
447458
}
448459
awayPitchers.append(pitcher)
449460

450-
"""Get away team totals"""
461+
#Get away team totals
451462
awayPitchers.append ({
452463
'namefield':'Totals',
453464
'ip':str(away['teamStats']['pitching']['inningsPitched']),
@@ -460,7 +471,7 @@ def boxscore(gamePk,battingBox=True,battingInfo=True,fieldingInfo=True,pitchingB
460471
'era':''
461472
})
462473

463-
"""Add home column headers"""
474+
#Add home column headers
464475
homePitchers = [{'namefield':teamInfo['home']['teamName'] + ' Pitchers', 'ip':'IP', 'h':'H', 'r':'R', 'er':'ER', 'bb':'BB', 'k':'K', 'hr':'HR', 'era':'ERA'}]
465476
for pitcherId_int in home['pitchers']:
466477
pitcherId = str(pitcherId_int)
@@ -479,7 +490,7 @@ def boxscore(gamePk,battingBox=True,battingInfo=True,fieldingInfo=True,pitchingB
479490
}
480491
homePitchers.append(pitcher)
481492

482-
"""Get home team totals"""
493+
#Get home team totals
483494
homePitchers.append ({
484495
'namefield':'Totals',
485496
'ip':str(home['teamStats']['pitching']['inningsPitched']),
@@ -492,13 +503,13 @@ def boxscore(gamePk,battingBox=True,battingInfo=True,fieldingInfo=True,pitchingB
492503
'era':''
493504
})
494505

495-
"""Make sure the home and away pitcher lists are the same length"""
506+
#Make sure the home and away pitcher lists are the same length
496507
while len(awayPitchers) > len(homePitchers):
497508
homePitchers.append({'namefield':'','ip':'','h':'','r':'','er':'','bb':'','k':'','hr':'','era':''})
498509
while len(awayPitchers) < len(homePitchers):
499510
awayPitchers.append({'namefield':'','ip':'','h':'','r':'','er':'','bb':'','k':'','hr':'','era':''})
500511

501-
"""Build the pitching box!"""
512+
#Build the pitching box!
502513
for i in range(0,len(awayPitchers)):
503514
if i==0 or i==len(awayPitchers)-1:
504515
boxscore += '-'*rowLen + ' | ' + '-'*rowLen + '\n'
@@ -507,7 +518,7 @@ def boxscore(gamePk,battingBox=True,battingInfo=True,fieldingInfo=True,pitchingB
507518
if i==0 or i==len(awayPitchers)-1:
508519
boxscore += '-'*rowLen + ' | ' + '-'*rowLen + '\n'
509520

510-
"""Get game info"""
521+
#Get game info
511522
if gameInfo:
512523
z = r['liveData']['boxscore'].get('info',[])
513524
gameBoxInfo = {}
@@ -530,7 +541,7 @@ def boxscore(gamePk,battingBox=True,battingInfo=True,fieldingInfo=True,pitchingB
530541
else:
531542
gameBoxInfo.update({len(gameBoxInfo): x['label'] + (': ' if x.get('value') else '') + x.get('value','') })
532543

533-
"""Build the game info box"""
544+
#Build the game info box
534545
for i in range(0,len(gameBoxInfo)):
535546
boxscore += ('{:<%s}'%fullRowLen + '\n').format(gameBoxInfo[i])
536547
if i==len(gameBoxInfo)-1:
@@ -599,7 +610,7 @@ def linescore(gamePk,timecode=None):
599610
str(r['liveData']['linescore'].get('teams',{}).get('home',{}).get('errors',0))
600611
])
601612

602-
"""Build the linescore"""
613+
#Build the linescore
603614
for k in [[header_name,header_row],[away_name,away],[home_name,home]]:
604615
linescore += ('{:<%s}' % str(len(max([header_name,away_name,home_name],key=len)) + 1)).format(k[0])
605616
linescore += ('{:^2}' * (len(k[1])-3)).format(*k[1])
@@ -786,7 +797,7 @@ def get(endpoint,params,force=False):
786797
return value will be the raw response from MLB Stats API in json format
787798
"""
788799

789-
"""Lookup endpoint from input parameter"""
800+
#Lookup endpoint from input parameter
790801
ep = ENDPOINTS.get(endpoint)
791802
if not ep: raise ValueError('Invalid endpoint ('+str(endpoint)+').')
792803
url = ep['url']
@@ -795,7 +806,7 @@ def get(endpoint,params,force=False):
795806
path_params = {}
796807
query_params = {}
797808

798-
"""Parse parameters into path and query parameters, and discard invalid parameters"""
809+
#Parse parameters into path and query parameters, and discard invalid parameters
799810
for p,pv in params.items():
800811
if ep['path_params'].get(p):
801812
if DEBUG: print ("Found path param:",p) #debug
@@ -819,7 +830,7 @@ def get(endpoint,params,force=False):
819830
if DEBUG: print ("path_params:",path_params) #debug
820831
if DEBUG: print ("query_params:",query_params) #debug
821832

822-
"""Replace path parameters with their values"""
833+
#Replace path parameters with their values
823834
for k,v in path_params.items():
824835
if DEBUG: print("Replacing {%s}" % k) #debug
825836
url = url.replace('{'+k+'}',v)
@@ -839,15 +850,15 @@ def get(endpoint,params,force=False):
839850
if DEBUG: print("Removing optional param {%s}" % param) #debug
840851
url = url.replace('{'+param+'}','')
841852
if DEBUG: print("URL:",url) #debug
842-
"""Add query parameters to the URL"""
853+
#Add query parameters to the URL
843854
if len(query_params) > 0:
844855
for k,v in query_params.items():
845856
if DEBUG: print("Adding query parameter %s=%s" % (k,v))
846857
sep = '?' if url.find('?') == -1 else '&'
847858
url += sep + k + "=" + v
848859
if DEBUG: print("URL:",url) #debug
849860

850-
"""Make sure required parameters are present"""
861+
#Make sure required parameters are present
851862
satisfied = False
852863
missing_params = []
853864
for x in ep.get('required_params',[]):
@@ -863,7 +874,7 @@ def get(endpoint,params,force=False):
863874
else: note = ''
864875
raise ValueError("Missing required parameter(s): " + ', '.join(missing_params) + ".\n--Required parameters for the " + endpoint + " endpoint: " + str(ep.get('required_params',[])) + ". \n--Note: If there are multiple sets in the required parameter list, you can choose any of the sets."+note)
865876

866-
"""Make the request"""
877+
#Make the request
867878
r = requests.get(url)
868879
if r.status_code not in [200,201]:
869880
raise ValueError('Request failed. Status Code: ' + str(r.status_code) + '.')

0 commit comments

Comments
 (0)