2

In my program, I use lots of blocks like this:

while True:

    try:
        DO_SOMETHING()
        break

    except:
        pass

Such that I can "keep trying until success". But this seems not Pythonic. Is there any elegant way to do this?

liyuanhe211
  • 671
  • 6
  • 15
  • 2
    Why it doesn't seem pythonic? Its looks perfectly okay to me, except for the `except: pass` part. – thefourtheye Jun 27 '15 at 10:19
  • 1
    Maybe you could make it a decorator? – tobias_k Jun 27 '15 at 10:20
  • @tobias_k How to make it a decorator? If it's really possible it would be the best solution here, in my opinion. – dlask Jun 27 '15 at 10:22
  • @dlask, as a similar question was found by Martijn Pieters, there is a package for this: https://pypi.python.org/pypi/retrying – liyuanhe211 Jun 27 '15 at 10:28
  • Well, I just wanted to post this as an answer, but now I can't. Anyway, seems like something similar does already exist. See [this answer](http://stackoverflow.com/a/25912659/1639625) on the duplicate question. – tobias_k Jun 27 '15 at 10:28
  • You can put your code in a function with DO_SOMETHING as an argument (and probably *pargs et **kargs to pass along the arguments). – Eric Levieil Jun 27 '15 at 11:31
  • depending on what it is, a callback might also be a decent option. they work well for asynchronous situations and most of the time would be non-blocking. the general idea is that instead of polling forever until something happens, a callback function is attached to an action of some sort. when that actions response comes back in, the function is fired. such a function could even be recursive, ie firing itself. – Justin Gourley Jun 27 '15 at 17:04

0 Answers0