mercredi 27 mars 2019

How to ensure functions are run in specific order Python

Im relatively new to python design patterns but I want to ensure my code is as understandable and flexible as possible. Here is an example:

data=query_data(sql)

transformed_data=transform_data(data, arg1, arg2)

train, test, validate = train_test_validate(transformed_data, frac_test, frac_validate)

model = fit_model(train,test, loss, learning_rate)

predictions, f1 = model.predict(validate)

Each function must run in this order. In this particular example the order should be very obvious. But in more complex modules there can be branching paths and it can be unclear without extensive documentation which order the functions should be run in.

It is simple enough to just wrap the module in another function that applies the functions in order but that seems to make a needlessly complex function with many arguments that violates single responsibility.

I've also tried to wrap each function in a class that returns the next class in the sequence which has the appropriate branching methods. This has the advantage that the order of the code is implied in the design of module and methods are only callable at appropriate times. This leads to many many classes, most with just one method where there are no branches. Ive been warned that this is a bad design pattern.

Is there a best way to ensure that code runs in a specific order and that that order is obvious from the design of the code?

Thank you so much for your help!

Aucun commentaire:

Enregistrer un commentaire