Useful Python Functions

Hey all!
I’ve not got much time, but I thought I’d share my python functions which are helping me at the moment!

merge_lists:
replace all items in list b with items in list a for each index in list a

def merge_lists(a, b):
    '''Replace all items in list b for each index available in list a
    '''
    for i, item in enumerate(a):
        b<i> = item

setdefaultdict:
[I]The same as dict.setdefault(key, value).

def setdefaultdict(dictionary, key, default):
    ''' Look for key and return value, setting a default value if it doesn't exist
    '''
    try:
        return dictionary[key]
    except KeyError:
        dictionary[key] = default
        return default

setdefaultattr:
use similarly to getattr() except it will set the value of object.key to the value and return that object.key value rather than return the value without setting it.

def setdefaultattr(obj, name, value):
    ''' Look for attribute and return it, setting a default value if it doesn't exist
    '''
    try:
        return getattr(obj, name)
    except AttributeError:
        setattr(obj, name, value)
    return value

setdefaultmethod:
Same function as setdefaultdict except it sets the value of a called function, and not the reference to it.

def setdefaultmethod(dictionary, key, default, args):
    ''' Look for key and return value, returning value of function if it doens't exist
    '''
    try:
        return dictionary[key]
    except KeyError:
        dictionary[key] = default(*args)
        return dictionary[key 

I see some efficiency issues with get_else_set_dict.

  • it adds the value to the dict regardless if it exist or not (unnecessary write access)
  • the code create a list with one item “method” - then your read the content and through away the list. I do not see for what you need the list. Creating lists costs processing time.
  • the code reads the dict again = reading + writing + reading

I suggest to do this:


def getFromDict(dictionary, key, default=None):
    '''
    Returns the value for the key from the dictionary. 
    If the key does not exist it will be added with the value of default.
    '''
    try:
        return dictionary[key]
    except KeyError:
        dictionary[key] = default
    return default

Be aware this is only good for simple default values. They has to be created before calling this function regardless if the key exist or not. Creating objects costs processing time and memory.

Similar with get_else_set_object
better something like this:


def getObjectAttribute(object_, attribute, default=None):
    '''
    Returns the provided attribute. 
    If such attribute does not exist the default value will be set and returned.
    '''
    try:
        return getattr(object_, attribute, method)
    except AttributeError:
        pass
    setattr(object_, attribute, default)
    return default 

It could happen that an object does not use a simple setter for it’s attribute (bad design). In this case it can make sense to read the attribute again rather than to return the default value.

Edit:
Your idea to pass a method as “default” as function call with parameters is pretty good.
I suggest to use a proper if…else or try…except statement. It would be much easier to understand.

For the most part, I considered using try except, but I had seen mixed performance. To be honest, the profiler hasn’t been much use in this respect.
However, the reason I return object[key] is because i want to return the reference, and not the value. My mistake.