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?
In general, there's absolutely nothing wrong with calling 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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With