Q:

How to dynamically pass predicates to filter function?

I have a dictionary named eval_params that looks like this:
In [1]: eval_params
Out[1]: 
{1: {'CLF': 'EMNB',
  'EM': 'False',
  'FEA': 'words',
  'NGRAM': '1-1',
  'PDS': 'T',
  'PSE': '-',
  'RN': '1dnf',
  'STEM': 'False',
  'UDS': 'He'},
 2: {'CLF': 'EMNB',
  'EM': 'False',
  'FEA': 'words',
  'NGRAM': '1-1',
  'PDS': 'TS',
  'PSE': '-',
  'RN': '1dnf',
  'STEM': 'False',
  'UDS': 'He'},
 3: {'CLF': 'EMNB',
  'EM': 'False',
  'FEA': 'words',
  'NGRAM': '1-1',
  'PDS': 'T',
  'PSE': '-',
  'RN': '1dnf',
  'STEM': 'False',
  'UDS': 'Te'}}

I have to filter this dictionary by certain predicates for which I use the built-in function filter:
In [2]: filter(pred_func, eval_params.iteritems())
Out[2]: 
[(3,
  {'CLF': 'EMNB',
   'EM': 'False',
   'FEA': 'words',
   'NGRAM': '1-1',
   'PDS': 'T',
   'PSE': '-',
   'RN': '1dnf',
   'STEM': 'False',
   'UDS': 'Te'})]    

My problem is that I don't want to hard-code the predicates inside pred_func but to pass them dynamically to pred_func. The current pred_func looks like this:
def pred_func((i, d)):
    # I have to hard-code the parameters to filter by. I don't want that
    return d['PDS'] == 'T' and d['UDS'] = 'Te'

Instead, I'd like to have something like:
def pred_func((i, d), predicates):
    vals = []
    # predicates would be a dictionary such as {'PDS':'T', 'UDS':'Te'}
    for param, val in predicates.iteritems():
        vals.append(d[param] == val)
    return all(vals)

However, as far as I know, I cannot pass extra arguments to the predicate function, so how can I accomplish what I want in an elegant way? Any idea?

A:

Create a higher-order function [wikipedia], i.e. a function that returns a function. For example:
def pred_func(predicates):
    # Define a function inside `pred_func`. This function is a "closure" and 
    # will have access to the `predicates` parameter
    def func((i, d)):
        # You can simply pass a generator to `all`
        return all(d[param] == val for param, val in predicates.iteritems())

    # Return the function
    return func

pred_func is now a function which returns a function that accepts a tuple as argument (just like your original pred_func function).
You can then call the function with:
filter(pred_func(predicates), eval_params.iteritems())

