Wednesday, January 18, 2012

Python dictionary with default values

The blog is now moved here

Recently, I had a task to call method with certain parameters passed to another function inside it. 

The code looks like this:

class SomeClass(object):    
    def some_method(self, arg2, params, kwarg1='default_value', 
                                        kwarg2='default_value'):        
        return external_module.meth(**params)
params is a dictionary with a few key-value pairs and it is often the same so we need default values. 
It is possible to do it as following: 
class SomeClass(object):    
    def some_method(self, arg2, kwarg1='default_value', 
                                kwarg2='default_value',
                                params_k1='default_value',
                                params_k2='default_value'):
        
        return external_module.meth(params_k1=params_k1,
                                        params_k2=params_k2)
But obviously it is not that elegant. I consider the following solution to be the best for such problem:
class SomeClass(object):

    default_params = {
        'params_k1': 'default_value',
        'params_k2': 'default_value'
    }

    def some_method(self, arg2, params):
        
        params = dict(self.default_params, **params)
        return external_module.meth(**params)
Note, should use
params = dict(self.default_params, **params)
instead of
params = self.default_params.update(params)
because second one would override default values itself. We need to keep original default values as they are. 

The key point here is that the keyword arguments have higher priority than the original dictionary passed as the first argument while building the resulting dictionary. Also dict()returns new instance of dict type which can be useful.


I found it really useful especially when you can't just pass parameters as regular keyword arguments.

No comments:

Post a Comment