More elegant way to try running a function X times?

Tim Chase python.list at tim.thechases.com
Wed Nov 19 09:23:12 EST 2008


> I need to try calling a function 5 times. If successful, move on; If
> not, print an error message, and exit the program:
> 
> success = None
> for i in range(5):
> 	#Try to fetch public IP
> 	success = CheckIP()
> 	if success:
> 		break
> if not success:
> 	print "Exiting."
> 	sys.exit()

Though a bit of an abuse, you can use

   if not any(CheckIP() for _ in range(5)):
     print "Exiting"
     sys.exit()

(this assumes Python2.5, but the any() function is easily 
recreated per the docs at [1]; and also assumes the generator 
creation of 2.4, so this isn't as useful in 2.3 and below)

Alternatively, you can use the for/else structure:

   for i in range(5):
     if CheckIP():
       break
   else:
     print "Exiting"
     sys.exit()

-tkc

[1]
http://www.python.org/doc/2.5.2/lib/built-in-funcs.html#l2h-10





.



More information about the Python-list mailing list