paris_serviola paris_serviola - 1 year ago 47
Python Question

How do you design python filter function to be able to sort using addition attribute?

I am creating different filters as part of my python library. I want each filter to be a function in a python module.

def filterB(num):
return num == 'B'

def filterA(str):
return str == 'A'

Each of these filter can be imported and added to the list .

import filters

my_list = [filters.filterA, filters.filterB]

Now , all these can be applied as ifilter to my list.

my_list = ['A', 'B' , 'C' , 'D']

def nFilter(filters, my_list):
for f in filters:
my_list = ifilter(f, my_list)
return my_list

Now, I also want each of these filter to have an order number so filter can be applied according to specific order. How would I achieve this because ifilter only takes function.

P.S. I have considered creating abstract filter class and interfacing it to my specific filter class. I am just looking for better design ways to solve this problem? So any opinion will be helpful.


If I understand you correctly: Make your filters list contain tuples of , and iterate over them in a sorted way.

import filters

filter_list = [(2, filters.filterA), (1, filters.filterB)]

data_list = ['A', 'B' , 'C' , 'D']

def nFilter(filters, my_list):
    for _, f in sorted(filters):
        my_list = ifilter(f, my_list)
    return my_list  # or list(my_list) if you actually want a list