Sean
Sean

Reputation: 992

Learn Python the Hard Way ex39

In exercise 39 of Learn Python the Hard Way (http://learnpythonthehardway.org/book/ex39.html), the following functions are defined (get_slot() and get()):

def get_slot(aMap, key, default=None):
    """
    Returns the index, key, and value of a slot found in a bucket.
    Returns -1, key, and default (None if not set) when not found.
    """
    bucket = get_bucket(aMap, key)

    for i, kv in enumerate(bucket):
        k, v = kv
        if key == k:
            return i, k, v
    return -1, key, default

def get(aMap, key, default=None):
    """Gets the value in a bucket for the given key, or the default."""
    i, k, v = get_slot(aMap, key, default=default)
    return v

Why write default=default when calling get_slot() ?

It would seem to me that simply calling get_slot() with 'default' would be sufficient? -> get_slot(aMap, key, default)

Is the default=default something to do with named vs positional function parameters? (as are discussed here: http://pythoncentral.io/fun-with-python-function-parameters/) or is the default=default done for a different reason entirely?

Upvotes: 2

Views: 632

Answers (1)

toti08
toti08

Reputation: 2454

default is a "key argument" for function get_slot() and its default value is None. When you call get_slot() without specifying "default", it takes the value "None". In the example above you're setting the key argument "default" to "default" which is the argument passed to the function "get", so it takes value None.

So in this particular case it doesn't change whether you call:

get_slot(aMap, key)

or

get_slot(aMap, key, default = default)

but if a value different from None was passed to the get function the default variable in your get_slot function would take a value different from None.

I hope this clears it a bit.

Upvotes: 1

Related Questions