r.headers['Authorization'] in python2.7 class's __call__ function
Question: I'm digging a little into requests/requests/auth.py file at master
kennethreitz/requests on github.

<https://github.com/kennethreitz/requests/blob/master/requests/auth.py>

And I saw this code,

    
    
    class HTTPBasicAuth(AuthBase):
    """Attaches HTTP Basic Authentication to the given Request object."""
    def __init__(self, username, password):
        self.username = username
        self.password = password
    
    def __call__(self, r):
        r.headers['Authorization'] = _basic_auth_str(self.username, self.password)
        return r
    

I just can't understand how could he comes up with r.headerp['Authorisation ']
which hasn't been defined anywhere before. Am I missing something?

Many thanks for someone to answer the problem :)


Answer: I'm assuming the r.headers object is just a dictionary datastructure.

In Python you can take a dictionary and assign any attribute, existing or not,
and if it doesn't exist already it'll be created.

You can see this if you fire up a python shell

    
    
    #Create a new empty dictionary, no attributes
    >>> obj = {}
    #Assign the string "hello header" to the "headers" attribute
    >>> obj['headers'] = "hello header"
    # Print it
    >>> print(obj['headers'])
    

> hello header

See [this](http://www.tutorialspoint.com/python/python_dictionary.htm) page on
python dictionary datastructures to learn more.

**EDIT:**

A 2 second glance at the source file you linked to shows the line

    
    
    from .utils import parse_dict_header, to_native_string
    

I think without looking into it it's safe to say the header attribute is just
a dictionary - `parse_dict_header`.

**EDIT 2:** To answer your more specific question as to where `r.headers`
comes from.

the `__call__` method is when the `HTTPBasicAuth` object is called like a
function which I could trace through the code and see happening
[here](https://github.com/kennethreitz/requests/blob/f5dacf84468ab7e0631cc61a3f1431a32e3e143c/requests/models.py)
at line 487 which is in the `prepare_auth` method of the `Request` object.

    
    
    r = auth(self)
    

where self is the `Request` object instance. The `Request` has the headers
attribute of itself set in the `__init__` at line 225.

    
    
    self.headers = headers
    

It is this `Request` object defined in `models.py` which is the parameter `r`
passed to the `__call__` method of the `HTTPBasicAuth` class.

If you use something like Python Visual Studio Calls you could run this code,
break on the line you're interested in, in this case where r.headers is used,
and see the backstack at that point and explore the objects in scope.

