Jimmy C
Jimmy C

Reputation: 9660

Can I change function parameters when passing them as variables?

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.

Upvotes: 2

Views: 87

Answers (1)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250881

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?

Upvotes: 5

Related Questions