Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
class APIWrapper:
#snippet...
def poll_api(self, tries, initial_delay, delay, backoff, success_list, apifunction, *args):
time.sleep(initial_delay)
for n in range(tries):
try:
status = self.get_status()
if status not in success_list:
polling_time = time.strftime("%a, %d %b %Y %H:%M:%S", time.localtime())
print("{0}. Sleeping for {1} seconds.".format(polling_time, delay))
time.sleep(delay)
delay *= backoff
else:
return apifunction(*args)
except socket.error as e:
print("Connection dropped with error code {0}".format(e.errno))
raise ExceededRetries("Failed to poll {0} within {1} tries.".format(apifunction, tries))
@encukou
Copy link

encukou commented Mar 1, 2013

You can just use delay directly, no need to "make it mutable". In fact, you can never make an int (or float) mutable, but you can assign a completely new object to a variable.
The line delay *= backoff would create a new immutable number object with value delay * backoff, and then assign that to the name delay. The old value of delay is forgotten.

@echohack
Copy link
Author

echohack commented Jun 1, 2013

wouldn't using delay directly cause the next call to poll_api use the old value of delay then?

Oh wait, I think I just answered my own question. No it wouldn't, because delay is immutable.

However, for parameters that are mutable, this could cause a problem I think.

Code updated! Thanks encukou!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment