Skip to content Skip to sidebar Skip to footer

How Are Functions Inside Functions Called? And Can I Access Those Functions Or They Work Like "helper Methods"?

I'm studying Python through The Python Tutorial and I'm currently at Classes (chapter 9), but during the explanation of 'scopes and namespaces' I got a question. The author give th

Solution 1:

Functions can be defined anywhere. They do not need to be defined inside classes, they can be defined inside other functions too; the are commonly referred to as nested functions in that case.

You cannot access the nested functions from outside the scope_test() function; they are local variables. That limitation applies to all local variables in a function. For example, the spam name defined inside scope_test is also not accessible outside of the function. They exist only for the duration of the function local scope.

The function could make them available by returning the function. Python functions are first class objects, so you can pass them around like other values, you can assign them other names, or you can just return them.

You could call them helper functions if you want to; in Python you normally nested functions if you want to make use of the nested scope, referring to variables defined in a parent scope. Decorators often make use of this (defining configuration for a wrapper function), as do event handlers.

Post a Comment for "How Are Functions Inside Functions Called? And Can I Access Those Functions Or They Work Like "helper Methods"?"