I know that they're a gcc extension and not standard, but I just wanted to know what makes them useful? Is there any task where using this extension makes things much easier than attempting to stick with the ISO standard?
I was reading up on decorators and they started off giving examples of nested functions to illustrate how decorations work. I didnโt really understand.
Take the following example code they give:
def split_string(function):
def wrapper():
func = function()
splitted_string = func.split()
return splitted_string
return wrapper
def say_hi():
return 'hello there
decorate = uppercase_decorator(say_hi)
decorate()In the nested function def wrapper(), why does this need to be nested at all. You could easily write a to_uppercase function without nesting it so what are the advantages of this way?
>>> def sum(x, y):
... def do_it():
... return x + y
... return do_it
...
>>> a = sum(1, 3)
>>> a
<function do_it at 0xb772b304>
>>> a()
4
Is this what you were looking for? It's called a closure.
You don't really gain much by doing this, in fact it slows method_a down because it'll define and recompile the other function every time it's called. Given that, it would probably be better to just prefix the function name with underscore to indicate it's a private method -- i.e. _method_b.
I suppose you might want to do this if the nested function's definition varied each time for some reason, but that may indicate a flaw in your design. That said, there is a valid reason to do this to allow the nested function to use arguments that were passed to the outer function but not explicitly passed on to them, which sometimes occurs when writing function decorators, for example. It's what is being shown in the accepted answer although a decorator is not being defined or used.
Update:
Here's proof that nesting them is slower (using Python 3.6.1), although admittedly not by much in this trivial case:
setup = """
class Test(object):
def separate(self, arg):
some_data = self._method_b(arg)
def _method_b(self, arg):
return arg+1
def nested(self, arg):
def method_b2(self, arg):
return arg+1
some_data = method_b2(self, arg)
obj = Test()
"""
from timeit import Timer
print(min(Timer(stmt='obj.separate(42)', setup=setup).repeat())) # -> 0.24479823284461724
print(min(Timer(stmt='obj.nested(42)', setup=setup).repeat())) # -> 0.26553459700452575
Note I added some self arguments to your sample functions to make them more like real methods (although method_b2 still isn't technically a method of the Test class). Also the nested function is actually called in that version, unlike yours.
So, I am writing a main function (so that I can say if name == "main" because that is good practice). And my main file accesses a lot of classes that are not inside of the main function. This is all fine, but then there is a function in a number of different classes that I want to call at once. Think of it like: reset_box(), reset_circle(), reset_triangle() or whatever.
Under certain conditions I want to just hit all these at once. So, it would be nice to have a function I can call that just does them all at once rather than writing them all out each time.
It would be easiest to do this in the main function, to just add in another function that resets everything. Or is this bad code? Should I take the function out of main and call it that way? The downside of this is that I have to pass it every object that I want to reset which will make it look a little ugly?
What are people's thoughts? Is it better to have a little function inside main that I can call to reset a bunch of objects. Or does it seem better to have the function out of main and just pass in every object that I need to?
One popular use of nested functions is closures. In a lexically scoped language with first-class functions it's possible to use functions to store data. A simple example in Scheme is a counter:
(define (make-counter)
(let ((count 0)) ; used to store the count
(define (counter) ; this is the counter we're creating
(set! count (+ count 1)) ; increment the count
count) ; return the new count
counter)) ; return the new counter function
(define mycounter (make-counter)) ; create a counter called mycounter
(mycounter) ; returns 1
(mycounter) ; returns 2
In this example, we nest the function counter inside the function make-counter, and by returning this internal function we are able to access the data available to counter when it was defined. This information is private to this instance of mycounter - if we were to create another counter, it would use a different spot to store the internal count. Continuing from the previous example:
(define mycounter2 (make-counter))
(mycounter2) ; returns 1
(mycounter) ; returns 3
It's useful for recursion when there is only 1 method that will ever call it
string[] GetFiles(string path)
{
void NestedGetFiles(string path, List<string> result)
{
result.AddRange( files in the current path);
foreach(string subPath in FoldersInTheCurrentPath)
NestedGetFiles(subPath, result);
}
List<string> result = new List<string>();
NestedGetFiles(path, result);
return result.ToArray();
}
The above code is completely made up but is based on C# to give the idea of what I mean. The only method that can call NestedGetFiles is the GetFiles method.
You cannot define a function within another function in standard C.
You can declare a function inside of a function, but it's not a nested function.
gcc has a language extension that allows nested functions. They are nonstandard, and as such are entirely compiler-dependent.
No, they don't exist in C.
They are used in languages like Pascal for (at least) two reasons:
- They allow functional decomposition without polluting namespaces. You can define a single publicly visible function that implements some complex logic by relying one or more nested functions to break the problem into smaller, logical pieces.
- They simplify parameter passing in some cases. A nested function has access to all the parameters and some or all of the variables in the scope of the outer function, so the outer function doesn't have to explicitly pass a pile of local state into the nested function.