2

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?

2
  • 4
    in this case it is the same, but it is generally good practice (safer) to also use the keyword argument names even when the position matches. Commented Dec 2, 2015 at 7:39
  • okay, so because 'default' is a named parameter, it is good practice to use the keyword argument 'default=' when calling the function? Have I understood correctly? Commented Dec 2, 2015 at 12:04

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks for your answer, for some reason, the person that edited my question changed the code from 'None' to '1' (I've changed that back and added a link to the Learn Python the Hard Way example so that people can see the code in-situ). Does this change your answer?
Thanks for clarifying. It actually changes the answer as in the end your default value will take the value None. The way the values are passed among the functions does not change, however the final result will. I'll update the answer!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.