Python

Why should we declare a function inside another function in Python

April 3, 2022

Why should we declare a function inside another function in Python

In this article we will learn why should we declare a function inside another function and also what this impacts on the code and how can we benefit from this technique!

declare a function inside another function thumb

What’s up programmer, ok? Let’s learn more about Python and functions!

This technique of declaring functions within functions is also known as encapsulation.

Let’s imagine you have a repetition inside a function of the same code, then the best alternative is to wrap this code in a function

And if this portion of code is not used outside of this main function, it makes no sense to put this inner function in the global scope.

This way is better because we don’t mess up the global scope, adding more code for programmers to check and test.

Instead we insert this new function only in the context that it will be used in

And this is not just a practice in Python, but in all other programming languages.

Let’s see an example:

def getNumber(num):
 result = 0
 
 def checkNumber(num):
  if(num < 0):
   return num + 5
  else: 
   return num - 5

 for x in range(5):
  result += checkNumber(num)
  
 print(result)

getNumber(10)

Here we have a for inside the function getNumber, which invokes the function checkNumber several times

So, using this encapsulation, we could call it in another condition as well, assuming that it will not be used outside of this context.

Conditionals could stay inside the for statement, but then we would lose the power of reusing and the code would be a little more complex to read

Conclusion

In this article we learned why should we declare a function inside another function

It’s a matter of code organization along with possible reuse, making the code more maintainable

In addition, this is not a practice exclusive to Python, but to all programming languages.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x