Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat happens to the variable in this case when it is overwritten with self?
    text
    copied!<p>I am downloading URLs in Python and need to detect 404s, so after some search I came up with:</p> <pre><code>import urllib class MyUrlOpener(urllib.FancyURLopener): def retrieve(self, url, filename=None, reporthook=None, data=None): self.file_was_found = True val = urllib.FancyURLopener.retrieve(self, url, filename, reporthook, data) return val def http_error_404(url, fp, errcode, errmsg, headers, data): url.file_was_found = False def download_file(url, saveas): urlaccess = MyUrlOpener() localFile, headers = urlaccess.retrieve(url, saveas) return urlaccess.file_was_found </code></pre> <p>My question is that if you look at the source code (Python 2.7) for FancyURLopener then you see: </p> <pre><code>def http_error(self, url, fp, errcode, errmsg, headers, data=None): """Handle http errors. Derived class can override this, or provide specific handlers named http_error_DDD where DDD is the 3-digit error code.""" # First check if there's a specific handler for this error name = 'http_error_%d' % errcode if hasattr(self, name): method = getattr(self, name) if data is None: result = method(url, fp, errcode, errmsg, headers) else: result = method(url, fp, errcode, errmsg, headers, data) if result: return result return self.http_error_default(url, fp, errcode, errmsg, headers) </code></pre> <p>Which is passing the <code>url</code> as the first parameter and not <code>self</code>. I thought that the first parameter to a function was always a reference to the class instance (by convention) and my code confirms this. So what happens to the <code>url</code> value?</p> <p><strong>UPDATE:</strong> It turns out that <code>data==None</code> so it was calling the first signature. This foiled my attempts to manually add the self parameter. As soon as I added the <code>=None</code> default to <code>data</code> in my <code>http_error_404</code> signature all was well (because it used the default).</p> <p>The <em>fixed</em> / <em>correct</em> signature is <code>def http_error_404(self, url, fp, errcode, errmsg, headers, data=None):</code></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload