1

I find that that nesting functions can make code more readable, and manageable, just like indenting can. However, there is a performance impact due to the reloading each nested function each time the outer function is called (see these Q's on Stack Overflow What is the performance overhead of nested functions? Is there an overhead when nesting functions in Python?).

Would it be possible to avoid this overhead by using a decorator or some other trick to avoid the issue?

Jinglesting
  • 509
  • 5
  • 16
  • 2
    Unless you have done some profiling that proves otherwise, this is a premature optimization (https://stackoverflow.com/questions/385506/when-is-optimisation-premature) you should not worry about. The time it takes to define a function is neglectable, especially when compared to the benefits it provides (see https://stackoverflow.com/questions/11241523/why-does-python-code-run-faster-in-a-function) – DeepSpace Mar 13 '19 at 11:35
  • You can't use a decorator (on the inner function) to do what you want, because they are executed _after_ the function has been defined. A decorator on the outer function _could_ technically work, but it would really be overkill. – L3viathan Mar 13 '19 at 11:40
  • Just define those functions at the top-level instead... no need to nest them if you don't need a closure. – bruno desthuilliers Mar 13 '19 at 12:23
  • The nested functions must be bound to the variables in the outer function that they use. How should that be achieved without any kind of overhead? – NoDataDumpNoContribution Mar 13 '19 at 14:09

0 Answers0