problems with hasattr() and custom __getattr__ inside urllib2

Gil Tal giltalgiltal at
Wed Aug 24 19:31:11 CEST 2005

I use urllib2 to download a redirected url and I get an exception from
the bowels of urllib2. It seems that urllib2 implements some super
sophisticated self check and tries to control the access to attributes
using lots of calls to hasattr(the builtin function) and a custom
__getattr__() on the Request class that perfroms some checks and raises
an AttributeError if it's not happy. The problem is that hasattr()
according to the docs is supposed to eat the exception and simply
return False, but in my case it surfaces to my code and stops the
regular flow. Here is the output and my code:

AttributeError: redirect_dict

Traceback (innermost last):

File "c:\Gigi\Dev\Python\Updater\Client\", line 1, in ?
  import os, sys, urllib2
File "c:\Gigi\Dev\Python\Updater\Client\", line 36, in ?
  download(url, filename, chunkSize)
File "c:\Gigi\Dev\Python\Updater\Client\", line 4, in download
  fin = urllib2.urlopen(url)
File "C:\Python24\Lib\", line 130, in urlopen
  return, data)
File "C:\Python24\Lib\", line 364, in open
  response = meth(req, response)
File "C:\Python24\Lib\", line 471, in http_response
  response = self.parent.error(
File "C:\Python24\Lib\", line 396, in error
  result = self._call_chain(*args)
File "C:\Python24\Lib\", line 337, in _call_chain
  result = func(*args)
File "C:\Python24\Lib\", line 539, in http_error_302
  if hasattr(req, 'redirect_dict'):
File "C:\Python24\Lib\", line 207, in __getattr__
  raise AttributeError, attr

import os, sys, urllib2

def download(url, filename, chunkSize):
    fin = urllib2.urlopen(url)
    parent_dir = os.path.dirname(filename)
    if parent_dir != '' and not os.path.exists(parent_dir):
    fout = open(filename, 'wb')
    info =
    print 'info:', info
    totalBytes = int(info['Content-Length'])
    downloadBytes = 0
    bytesLeft = totalBytes
    while bytesLeft > 0:
        chunk =
        readBytes = len(chunk)
        downloadBytes += readBytes
        bytesLeft -= readBytes
        print 'Progress: %d/%d' % (downloadBytes, totalBytes)

    print 'Done.'

if __name__=="__main__":

    #url = ''
    url =


    filename = url.split('/')[-1]
    chunkSize = 1
    download(url, filename, chunkSize)
    print open(filename).read()

Thanks, Gil

More information about the Python-list mailing list