This kind of a broad question.
As I find myself having to write longer and longer scripts, I find that my instinct is to break everything up into bite-sized functions; however, this ultimately results in functions calling functions calling functions calling functions…. and I’m wondering if I’m completely thinking about this the wrong way.
Here’s what an abridged script might look like. Sorry it’s kind of contrived.
def simple_task_1():
return
def simple_task_2():
return
def simple_task_3():
return
def simple_task_4():
return
def complex_task_1():
simple_task_2()
simple_task_3()
simple_task_4()
return
def startup():
simple_task_1()
complex_task_1()
simple_task_4()
def finish():
# other function calls
return
def main():
startup()
finish()
So, is this the correct way to be using functions? Is there an objective point where you can say you’ve made too many function calls inside each other? Should I even be making functions for tasks that only end up being done once?
Python has a “recursion” limit. If you hit that, then you’re probably using too many functions, otherwise it’s probably not a big deal — Usually you can only hit the recursion limit if you’re calling a function recursively (and then usually because you did something wrong and didn’t break when you should have).
The point of functions is to make your life easier. If you find that you have too many functions and you’re not actually making your life easier, then it’s probably a problem. For example:
Is a pretty pointless function and it’s probably best avoided, however, if you want
sinc:That might actually be useful since the new function name is more descriptive than the code which is executed within. Also, later if you find that you need to remove the singularity at x=0, you can add that into
sinceasily.Ultimately, readability is what counts. If using a function makes your code easier to read, then it’s probably worthwhile (even if you’ll only call it from one place and could inline it easily). There are some grey areas if you’re really concerned about performance (functions do take a little longer to execute than inline code), but you shouldn’t use that as an excuse to inline something that is hard to read unless you can reliably demonstrate that it is a performance bottleneck.