1

im getting a type error and my class is using self in its function dl()

import urllib
import httplib
import os.path

###SAI22 Library###



def exists(site):
    conn = httplib.HTTPConnection(site)
    conn.request("HEAD",site)
    response = conn.getresponse()
    conn.close()
    return response.status == 200

class sai_download:
    def dl(self,_dir,_url,pck):
        if pck == True:
            if exists(_url) == True:
                urllib.urlretrieve(_url,_dir)
                if os.path.isfile(_dir) == True:
                    print "Download successful"
                    return True
                else:
                    print "Download failed"
                    return False
            else:
                print "Url isnt valid"
                return False


        elif pck == False:
            if exists(_url) == True:
                urllib.urlretrieve(_url,_dir)
                return True
                if os.path.isfile(_dir) == True:
                    return True
                else:
                    return False
            else:
                return False

When ran I get the type error but I have self in the class function dl, what I do wrong?

>>> s = sai_download()
>>> s.dl("C:\hh.html","http://stackoverflow.com/questions/82831/check-if-a-file-exists-using-python")

Traceback (most recent call last):
  File "<pyshell#41>", line 1, in <module>
    s.dl("C:\hh.html","http://stackoverflow.com/questions/82831/check-if-a-file-exists-using-python")
TypeError: dl() takes exactly 4 arguments (3 given)
>>>  
abarnert
  • 354,177
  • 51
  • 601
  • 671
YoungerDryas
  • 114
  • 2
  • 10
  • As a side note, all those `== True` comparisons are unnecessary; just use `if exists(_url):`. Or, in the last example, just `return os.path.isfile(_dir)`. – abarnert Dec 13 '14 at 02:12
  • Also, it's very weird to name all your parameters as "private" variables with underscore prefixes. What's wrong with just `def dl(self, dir, url, pck):`? It looks like you're borrowing an idiom made for some other language (maybe one with implicit `self`, or JS-style implicit globals) that isn't appropriate in Python and just makes your code less readable. – abarnert Dec 13 '14 at 02:13
  • PS, you need a blank line before an indented block to format it as code. (I've fixed this one for you, but for future reference…) – abarnert Dec 13 '14 at 02:14

1 Answers1

5

You need to define the pck parameter.

s.dl("C:\hh.html","http://stackoverflow.com/questions/82831/check-if-a-file-exists-using-python", True)

or if you want to make the parameter optional with a default value define the method like this:

def dl(self,_dir,_url,pck=True):
MarcSB
  • 1,040
  • 1
  • 12
  • 19