Type error in python program
Question: I always get a Type Error when I run the following python code (abc.py) as
follows:

    
    
    ./abc.py activatelink alphabeta
    Type Error: ['alphabeta']
    

My code:

    
    
    #!/usr/bin/python
    
    import urllib2
    from urllib2 import URLError
    from urllib2 import HTTPError
    import requests
    import urllib
    import json
    import time
    import os
    import sys
    import hashlib
    
    
    def activate_user(link):
            print invoke_rest('GET', link)
    
    def invoke_rest(request_type, rest_url, payload, headers):
            try:
                    api_url = rest_url
                    if request_type == 'GET':
                            r = requests.get(api_url)
                            to_ret = {'code':r.status_code, 'reply':r.text}
                            return to_ret
                    elif request_type == 'POST':
                            r = requests.post(api_url, data=payload, headers=headers)
                            to_ret = {'code':r.status_code, 'reply':r.text}
                            return to_ret
                    else:
                            return "Invalid request type ", request_type
            except Exception, e:
                    return "Exception:", e, " in getting the API call"
    
    def help():
        print ('Usage: %s { activate | help }', os.path.basename(sys.argv[0])
    
    if __name__ == '__main__':
        actions = {'activatelink': activate_user, 'help': help}
        try:
            action = str(sys.argv[1])
        except IndexError:
            print "IndexError: ", sys.argv[1]
            action = 'help'
        args = sys.argv[2:]
        try:
            actions[action](*args)
        except (KeyError):
            print "Key Error:", args
            help()
        except (TypeError):
            print "Type Error:", args
            help()
    

Am I doing anything wrong? I added some other functions other than
activatelink, which work fine, can anyone point out whats wrong in here?


Answer: Your `invoke_rest()` function takes _four_ arguments:

    
    
    def invoke_rest(request_type, rest_url, payload, headers):
    

but you pass in just the two:

    
    
    print invoke_rest('GET', link)
    

That raises a `TypeError` exception:

    
    
    >>> def invoke_rest(request_type, rest_url, payload, headers):
    ...     pass
    ... 
    >>> invoke_rest('GET', 'alphabeta')
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: invoke_rest() takes exactly 4 arguments (2 given)
    

Perhaps you wanted those two extra arguments (`payload` and `headers`) to be
optional. If so, make them keyword arguments and set their default value to
`None`:

    
    
    def invoke_rest(request_type, rest_url, payload=None, headers=None):
    

which is fine by the `requests` library.

