While loop decorator
<p>I am using the <code>ftp</code> library which is incredibly finicky when downloading a bunch of files. This will error about once every 20 tries:</p>

<pre><code>ftp.cwd(locale_dir)
</code></pre>

<p>So, what I do which fixes it is:</p>

<pre><code>while True:
    try:
        ftp.cwd(locale_dir)
    except:
        continue
    break
</code></pre>

<p>How would I write a python decorator to do this, as I have to do the above on about 10 ftp commands in a script. It would be nice if I could have something like:</p>

<pre><code>retry_on_failure(ftp.cwd(locale_dir))
</code></pre>

<p>You can't use the syntax you want, because in that code <code>ftp.cwd(locale_dir)</code> gets called before <code>retry_on_failure</code>, so any exception it raises will prevent the <code>retry</code> function from running. You could separate the function and its arguments, however, and call something like <code>retry_on_failure(ftp.cwd, (locale_dir,))</code>.</p>

<p>Here's an implementation that would work with that syntax. (Note, this isn't a decorator, as that's usually meant in Python.)</p>

<pre><code>def retry_on_failure(func, args=(), kwargs={}):
    while True:
        try:
            return func(*args, **kwargs)
        except Exception:
            pass
</code></pre>

<p>This will of course run forever if the function <em>always</em> raises an exception, so use with care. You could add a limit to the number of repetitions or add logging if you wanted to.</p>

python