2

Excuse my poor wording in the title, but here's a longer explanation:

I have a function which as arguments takes some functions which are used to determine which data to retrieve from a database, as such:

def customer_data(customer_name, *args):
    # initialize dictionary with ids
    codata = dict([(data.__name__, []) for data in args])
    codata['customer_observer_id'] = _customer_observer_ids(customer_name)

    # add values to dictionary using function name as key
    for data in args:
        for coid in codata['customer_observer_id']:
            codata[data.__name__].append(data(coid))
    return codata

Which makes the call to the function looking something like this:

customer_data('customername', target_parts, source_group, ...)

One of these functions is defined with an extra parameter:

def polarization_value(customer_observer_id, timespan='day')

What I would like is a way to change the timespan variable in a clever way. One obvious way is to include a keyword argument in customer_observer and add an exception when the function name being called is 'polarization_value', but I have a feeling there is a better way to do this.

1 Answer 1

5

You can use functools.partial and pass polarization_value as :

functools.partial(polarization_value, timespan='day')

Example:

>>> import functools
def func(x, y=1):
    print x, y
...     
>>> new_func = functools.partial(func, y=20)
>>> new_func(100)
100 20

You may also find this helpful: Python: Why is functools.partial necessary?

1
  • 2
    Yea, this is a partial application. Oct 26, 2013 at 11:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.