Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is defining an inner function inside a recursive function a bad idea?

I have some recursive backtracking code that tests if a choice is valid before making it. Is it a bad idea to nest the is_legal_choice function inside the recursive solve function? Will this inner function be redefined each time the solve function is called?

like image 843
rookie Avatar asked Apr 17 '14 16:04

rookie


People also ask

Is it bad to call a function inside a function?

In general, there's absolutely nothing wrong with calling a function inside a function.

Should you define a function inside a function?

It's actually fine to declare one function inside another one. This is specially useful creating decorators. However, as a rule of thumb, if the function is complex (more than 10 lines) it might be a better idea to declare it on the module level.

Are nested functions bad?

no, there's nothing wrong with that at all, and in js, it's usually a good thing. the inside functions may not be a pure function, if they rely on closure variables. If you don't need a closure or don't need to worry about polluting your namespace, write it as a sibling.

Can you define function inside another function?

A function defined inside another function is called a nested function. Nested functions can access variables of the enclosing scope. In Python, these non-local variables are read-only by default and we must declare them explicitly as non-local (using nonlocal keyword) in order to modify them.


2 Answers

Yes, the inner function will be redefined each time the function is called. However, it's not as bad as you might assume; the Python code is parsed into a code object once, and only the function object (which serves as a sort of wrapper for the code object) is built anew each time through.

like image 187
kindall Avatar answered Nov 18 '22 03:11

kindall


Yes, it will be redefined every time it is called. However, it's not always a bad idea. This is how you would make a closure, which is sometimes useful.

If your is_legal_choice function needs to use some data that's only available within the scope of the outer function I'd say go for it. The performance overhead won't be too big (you can always profile if you need to).

If is_legal_choice doesn't need any data from solve's parameters, do whatever makes your code most understandable.

You can find more information on closures with google, but here's an example: http://ynniv.com/blog/2007/08/closures-in-python.html

like image 34
bgschiller Avatar answered Nov 18 '22 02:11

bgschiller