This is a very close analogue to How to start at a specific step in a script?, arguably a duplicate.
Maybe this is more of a request for code review/critique. Having hardcoded integers in the code certainly works, but I’m trying to figure out a way to expose an intuitive argument to users that let’s them start the process at a given point. Technically they do all depend on each other, so a simple if/else won’t do.
restart_at_point = <get argument from job with widgets>
restart_map = {
"initial": 0,
"loans": 1,
"transactions": 2,
"collections": 3,
"customer_contacts": 4
}
restart_index = restart_map[restart_at_point]
if restart_index <= restart_map["loans"]:
loans()
if restart_index <= restart_map["transactions"]:
transactions()
if restart_index <= restart_map["customer_contacts"]:
customer_contacts()
This works but I worry that it’s a bit confusing. Would it be more clear to have it be like:
def loans():
... # do loan stuff
transactions()
def transactions():
... # do transaction stuff
collections()
def collections():
... # do collections stuff
customer_contacts()
def customer_contacts():
... # do customer contact stuff
restart_at_point = <get argument from job with widgets>
if restart_point == "loans":
loans()
if restart_point == "transactions":
transactions()
...
...
if restart_point == "customer_contacts":
customer_contacts()
This seems bad because the behavior of each function is not self-contained. It does it’s own thing, but then also has to tip the next domino.
>Solution :
If the end goal here is to call a sequence of functions and be able to start from essentially anywhere in the sequence based on user input, one possible (if naïve) approach would be to simply put all of those functions into a list (or perhaps better, a tuple) and then define another function to iterate over that list (calling the functions) starting at a given index.
# define the necessary functions
def a():
print('foo')
def b():
print('bar')
def c():
print('baz')
# define the order of function execution
seq = (a, b, c)
# define a function to run the sequence starting from the desired index
def run(index=0):
for fn in seq[index:len(seq)]:
fn() # call the function
run(1) # [example] start calling the sequence functions at index 1
>>> bar
>>> baz