Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chaining function calls in main. Is it "Pythonic"? [closed]

Tags:

python

Lately, some of my code has led me to a question about using outputs of functions as variables, then to use those same variables as parameters in other functions. All when defining main. I believe this can lead to errors when debugging and confusion when using a file as a module.

An example is below:

def add_two_numbers(x, y):
    z = x + y
    return z

def now_divide_two(z, s):
    t = z / s 
    return t

First method:

def main():
    added = add_two_numbers(5, 10)
    final_output = now_divide_two(added, 3)
    print(final_output)

Second method:

def main():
    final_output = now_divide_two(add_two_numbers(5,10), 3)
    print(final_output)

Style guides and good practice suggest the first method is superior to the second. Yet, I still feel that they are both "unpythonic". With that, let's assume functions become more complicated, but still require the principle of using each others outputs as the next one's parameters. What is the recommended methodology for running functions in main?


1 Answers

There's nothing unpythonic about passing the results of a function to another function. It's often the best way of doing things.

The first style is better than the second style in terms of clarity because it's a lot easier to tell what the value being passed to now_divide_two represents. In the second method, you aren't declaring the variable to be passed to now_divide_two, so you have to guess what the value you're passing represents. In the first method, there is a variable with a name, so you know reasonably well what the variable means and why you are passing it to another function.

Sometimes, however, it's easy to assume what the arguments to functions mean (like str for example), and in those cases it can be better to just pass the results of the function directly to the other function.

like image 163
Pika Supports Ukraine Avatar answered Jun 05 '26 13:06

Pika Supports Ukraine



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!