Returning False
Don't return False when something goes wrong. Return False when indicating state for example an in_good_state() or a logged_in() function should return True or False.
Using Asserts
Use assert statements for your internal logic that you don't expect the user of your API to have to handle. These are only there as a warning to alert you as soon as possible if the code is misbehaving.
Raising Exceptions
For any other circumstances use an exception
Example:
import time
import requests
class WebSiteAPI():
def __init__(self):
self.sessions = {}
def login(self, user, passwd):
timeout = 10
if user not in self.sessions:
self.add_user(user)
Using an assert
#here we are testing internal logic that we don't expect to ever need to be handled
#so we use an assert statement
assert user in self.sessions
#log in the user
self.call(user, 'http://udacity.com/login',
params={'username': user, 'password': passwd})
#make sure the login was successful
for i in range(timeout):
if self.logged_in():
return
time.sleep(1)
else:
Raising an exception
#it is likely the user of our API would want to take action
#if we timeout so we use an exception here
raise TimeOutError('failed to login %s with the password %s' % (user, passwd))
Returning state
def logged_in(self, user):
'''checks if the indicated user is logged in'''
#returning false should be done with functions that indicate state,
#not because something went wrong inside a function
if user not in self.sessions:
return False
if user in self.call(user, 'http://udacity.com/current-users'):
return True
else:
return False
def add_user(user):
'''creates a new session for the user passed into this function
the session will persist cookies across different api calls'''
self.sessions[user] = request.session()
def call(user, url, *args, **kwargs):
'''performs an api call
for each user who calls this function the cookies for that user
are remembered, kept, and reused the next time that user calls this function'''
return self.sessions[user].get(url, args, kwargs).content
class TimeOutError(Exception):
pass
using the above WebSiteAPI class
api = WebSiteAPI()
my_user = 'mrme'
api.login(my_user, 'awesome_password')
api.call(my_user, 'http://udacity.com/edit-page')