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 may create decorator as:</p>

<pre><code>def retry_on_failure(count=10): # &lt;- default count as 10
    def retry_function(function):
        def wrapper(*args, **kwargs):
            while count &gt; 0:
                try:
                   func_response = function(view, request, *args, **kwargs)
                   break  # &lt;- breaks the while loop if success 
                except:
                   count -= 1
                   func_response = None
            return func_response
        return wrapper
    return retry_function
</code></pre>

<p>Now create your file download function with this decorator as:</p>

<pre><code>@retry_on_failure(count=20)  # &lt;- will make attempts upto 20 times if unable to downlaod 
def download_file(file_name):
    ftp.cwd(file_namee)
</code></pre>

<p>You may use this decorator with any function, where you need to make a retry attempt in case of any exception (not just your file download function). This is the beauty of <code>decorators</code>, these are generic adoptable by any function ;)</p>

<p>In order to make a call to <code>download_file</code> fuction, just do: </p>

<pre><code>download_file(file_name)
</code></pre>

python