user3603880
user3603880

Reputation: 11

Function calls in a sequence

I am writing a program that must solve a task and the task has many points, so I made one function for each point.

In the main function, I am calling the functions (which all return a value) in the following way:

result = funcD(funcC(funcB(funcA(parameter))))

Is this way of setting function calls right and optimal or there is a better way?

Upvotes: 0

Views: 191

Answers (3)

owenwater
owenwater

Reputation: 811

First, as everyone else said, your implementation is totally valid, and separate into multiple lines is good idea to improve readability.

However, if there are even more that 4 functions, I have a better way to make your code more simple.

def chain_func(parameter, *functions):
    for func in functions:
        parameter = func(parameter)
    return parameter

This is based on python can pass function as a variable and call it in other function.

To use it, just simple chain_func(parameter, funcA, funcB, funcC, funcD)

Upvotes: 2

BartoszKP
BartoszKP

Reputation: 35891

If what they do and what they return is fixed, then also the dependency between them is fixed. So you have no other way then call them in this order. Otherwise there is no way of telling without knowing what do they do exactly.

Whether you pin a reference to the partial results:

result1 = funcA(parameter)
#...
result = funcD(result3)

or call them as you've presented in your question doesn't make a significant difference.

Upvotes: 1

Reticulated Spline
Reticulated Spline

Reputation: 2012

There's nothing really wrong with that way. You could improve readability by instead calling them like this:

resultA = funcA(parameter)
resultB = funcB(resultA)
resultC = funcC(resultB)
resultD = funcD(resultC)

But that's really just a matter of personal preference and style.

Upvotes: 1

Related Questions