简体   繁体   中英

Which Python pattern to use for dynamically selecting and ordering a filtered list of functions?

I have a growing list of general purpose re-usable validation checks, similar to this list below:

 1. check_product_name()
 2. check_product_price_within_range()
 3. check_product_expiration_date()
 4. check_product_sizes()
 5. check_foo()
 6. check_bar()
 7. ...

I also have a growing list of clients. Client A may want to implement validations 1-5, while Client B may want to implement validations 3, 6, and 4 (in that order).

Right now I'm considering a simple approach like below. (Pseudo-code, the actual configuration will be stored within a database)

client_a_validations = ['check_product_name', 'check_product_price_within_range', 'check_product_expiration_date', 'check_product_sizes', 'check_foo']
client_b_validations = ['check_product_expiration_date', 'check_foo', 'check_product_sizes']

My question is, is there a better more established pattern I could be referencing to solve this problem?

As I understand Django can be a good example. Django have two entities - form field and validator and one field can have multiple validators.

from django import forms

class MyForm(forms.Form):
    even_field = forms.IntegerField(validators=[validate_even, max_value])

So it's similar to your case and you chose a right pattern.

If number of validators really big you can define a group of validators.

For example:

check_all_product_specs = [check_product_name, check_product_price_within_range,
check_product_expiration_date]

client_a_validations = [check_all_product_specs, check_bar]

And before validation just expand this nested structure to flat list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM