Conceptcore
Local and nested functions
Also called nested function, local function, inner function, nested procedure.
A local or nested function is a function defined inside another function. Only the outer function can call it by name, and in most languages it can use the variables of the outer function.
- Applies to
- core-languages
Idea
A local function, also called a nested function, is a function defined inside another function. Its name is visible only inside the outer function, so other code cannot call it. In most languages that have them, the inner function can also read the variables and the parameters of the outer function.
Wikipedia defines it: "a nested function (or nested procedure or subroutine) is a named function that is defined within another (enclosing) block and is lexically scoped within the enclosing block – meaning it is only callable by name within the body of the enclosing block and can use identifiers declared in outer blocks, including outer functions."1
def sum_of_scaled(values, factor):
def scale(x):
return x * factor
total = 0
for v in values:
total += scale(v)
return total
print(sum_of_scaled([1, 2, 3], 10))
60
The function scale exists only inside sum_of_scaled. It reads factor, which is a parameter of the outer function, so the call scale(v) needs only one argument.
How it works
- The scope of the name. The inner function is a local name of the outer function. "The scope of a nested function is the block that contains it – be it a function block or block within a function body. It is not visible (cannot be called by name) outside its containing block."1
- The outer variables. The inner function uses the rules of Lexical scope. "A nested function can use identifiers (i.e. the name of functions, variables, types, classes) declared in any enclosing block, except when they are masked by inner declarations with the same names."1
- When the definition runs. In Python, a
defin a function body binds the name of the inner function in the block of the outer function. "If a name is bound in a block, it is a local variable of that block, unless declared as nonlocal or global."2 - The life of the inner function. If the outer function returns the inner function or stores it, the inner function can outlive the call. Then it is a closure. See Closure.
- The implementation. "Implementation of nested functions can be more involved than it may appear, as a reference to a nested function that references non-local variables creates a closure."1 A classic compiler reaches an outer variable through links between the stack frames: "Any non-local object, X, is reached via access-links in the activation frames on the machine stack."1
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Idiom | |
| Java | Idiom | |
| C | Absent | |
| C# | Native | |
| JavaScript | Native | |
| TypeScript | Native | |
| Go | Idiom | |
| Rust | Native | |
| Kotlin | Native | Kotlin supports local functions, which are functions declared inside other functions. No example file exists because kotlinc is not installed. |
| SQL | Does not apply | Standard SQL queries do not declare functions. |
| Bash | Idiom | |
| PowerShell | Idiom | A PowerShell function can define another function in its body, and the inner function is in the scope of the outer function. No example file exists because pwsh is not installed. |
| HTML | Does not apply | HTML is a markup language and has no functions. |
| CSS | Does not apply | CSS has no user-defined functions. |
| Regular expressions | Does not apply | A regular expression has no functions. |
- Python. A
defstatement can appear in a function body. The inner function reads the outer variables. To assign to one, it must declare itnonlocal. "The nonlocal statement causes the listed identifiers to refer to names previously bound in nonlocal scopes."3 - JavaScript. A function declaration can appear in a function body. "A function defined inside another function can also access all variables defined in its parent function, and any other variables to which the parent function has access."4
- TypeScript. The rules are the same as in JavaScript. The inner function can have type annotations.
- Java. A method cannot contain a method. A block holds only these statements: "BlockStatement: LocalClassOrInterfaceDeclaration LocalVariableDeclarationStatement Statement"5. So a method can declare a local class, or a local variable that holds a lambda.
- C#. "A local function is a named function declared inside another member, such as a method or constructor. Its name is in scope only within that member."6 "A non-static local function can use parameters and local variables from its containing member. This use is called capture."6
- C. Standard C has no nested functions: "each function definition must appear at file scope"7. GCC has them as an extension: "Nested functions are supported as an extension in GNU C, but are not supported by GNU C++."8
- C++. "A non-member function definition may appear at namespace scope only (there are no nested functions)."9 A lambda expression in the function body does the same work.
- Go. A function declaration is a top-level declaration: "TopLevelDecl = Declaration | FunctionDecl | MethodDecl ."10 In a function body, a Go program assigns a function literal to a variable. "Function literals are closures: they may refer to variables declared in a surrounding function."10
- Rust. A
fnitem can appear in a block, and "Declaring an item within a statement block restricts its scope to the block containing the statement."11 But the innerfncannot use the outer variables: "There is no implicit capture of the containing function’s generic parameters, parameters, and local variables."11 A closure can capture them: "Unlike functions, closures can capture values from the scope in which they’re defined."12 - Bash. A function definition is a command, and "This defines a shell function named fname."13 A definition inside a function body runs when the outer function runs, and the new function is not local to the outer function. Bash variables use dynamic scope: "The value of a variable that a function sees depends on its value within its caller"13.
def sum_of_scaled(values, factor):
def scale(x):
return x * factor
total = 0
for v in values:
total += scale(v)
return total
print(sum_of_scaled([1, 2, 3], 10))
print(sum_of_scaled([4], 2))
60
8
- Verdict: native. A
defin a function body defines a nested function. It reads the parameterfactorof the outer function.
#include <iostream>
#include <vector>
int sum_of_scaled(const std::vector<int>& values, int factor) {
auto scale = [factor](int x) { return x * factor; };
int total = 0;
for (int v : values) {
total += scale(v);
}
return total;
}
int main() {
std::cout << sum_of_scaled({1, 2, 3}, 10) << "\n";
std::cout << sum_of_scaled({4}, 2) << "\n";
}
60
8
- Verdict: idiom. C++ has no nested functions. A lambda in the function body captures
factorand works as a local function.
import java.util.function.IntUnaryOperator;
public class Main {
static int sumOfScaled(int[] values, int factor) {
IntUnaryOperator scale = x -> x * factor;
int total = 0;
for (int v : values) {
total += scale.applyAsInt(v);
}
return total;
}
public static void main(String[] args) {
System.out.println(sumOfScaled(new int[] {1, 2, 3}, 10));
System.out.println(sumOfScaled(new int[] {4}, 2));
}
}
60
8
- Verdict: idiom. A Java method cannot contain a method. A local variable holds a lambda, which can read the effectively final parameter
factor.
#include <stdio.h>
static int scale(int x, int factor) {
return x * factor;
}
static int sum_of_scaled(const int *values, int n, int factor) {
int total = 0;
for (int i = 0; i < n; i++) {
total += scale(values[i], factor);
}
return total;
}
int main(void) {
int a[] = {1, 2, 3};
int b[] = {4};
printf("%d\n", sum_of_scaled(a, 3, 10));
printf("%d\n", sum_of_scaled(b, 1, 2));
return 0;
}
60
8
- Verdict: absent. Standard C has no nested functions. A
staticfunction at file scope is private to the file, and it getsfactoras a parameter.
using System;
class Program
{
static int SumOfScaled(int[] values, int factor)
{
int total = 0;
foreach (int v in values)
{
total += Scale(v);
}
return total;
int Scale(int x)
{
return x * factor;
}
}
static void Main()
{
Console.WriteLine(SumOfScaled(new[] { 1, 2, 3 }, 10));
Console.WriteLine(SumOfScaled(new[] { 4 }, 2));
}
}
60
8
- Verdict: native.
Scaleis a local function. It captures the parameterfactorof the containing method.
function sumOfScaled(values, factor) {
function scale(x) {
return x * factor;
}
let total = 0;
for (const v of values) {
total += scale(v);
}
return total;
}
console.log(sumOfScaled([1, 2, 3], 10));
console.log(sumOfScaled([4], 2));
60
8
- Verdict: native. A function declaration in a function body is local to that function and can read its parameters.
function sumOfScaled(values: number[], factor: number): number {
function scale(x: number): number {
return x * factor;
}
let total = 0;
for (const v of values) {
total += scale(v);
}
return total;
}
console.log(sumOfScaled([1, 2, 3], 10));
console.log(sumOfScaled([4], 2));
60
8
- Verdict: native. A nested function declaration can have type annotations like any other function.
package main
import "fmt"
func sumOfScaled(values []int, factor int) int {
scale := func(x int) int {
return x * factor
}
total := 0
for _, v := range values {
total += scale(v)
}
return total
}
func main() {
fmt.Println(sumOfScaled([]int{1, 2, 3}, 10))
fmt.Println(sumOfScaled([]int{4}, 2))
}
60
8
- Verdict: idiom. Go declares functions only at the top level. A function literal in a local variable is a closure over
factor.
fn sum_of_scaled(values: &[i32], factor: i32) -> i32 {
fn scale(x: i32, factor: i32) -> i32 {
x * factor
}
let mut total = 0;
for &v in values {
total += scale(v, factor);
}
total
}
fn main() {
println!("{}", sum_of_scaled(&[1, 2, 3], 10));
println!("{}", sum_of_scaled(&[4], 2));
}
60
8
- Verdict: native. Rust allows a
fnitem in a function body, but the item cannot capture the outer variables, soscaletakesfactoras a parameter. A closure can capture it instead.
sum_of_scaled() {
local factor=$1
shift
scale() {
echo $(( $1 * factor ))
}
local total=0 v
for v in "$@"; do
total=$(( total + $(scale "$v") ))
done
echo "$total"
}
sum_of_scaled 10 1 2 3
sum_of_scaled 2 4
60
8
- Verdict: idiom. A function defined in a function body becomes a global function when the outer function runs. It sees the local
factorbecause Bash uses dynamic scope.
Variations and related ideas
- Inner functions and lambdas. A lambda can also be defined in a function body and use the outer variables. The C# guide compares them: a local function is the better choice when "The helper benefits from a name, has several statements, needs recursion, or is called from more than one place in the containing member."6 Wikipedia says that a lambda "has no name (is anonymous) and therefore cannot be called by name"1. See Higher-order function.
- Static local functions. C# lets a local function declare that it uses no outer state: "A static local function can't capture local variables, parameters, or instance state from the containing member."6 A Rust inner
fnis always like this11. - Recursive helpers. "A nested function typically acts as a helper function or a recursive function."1 In C#, "Local functions work well for recursion because their names are in scope throughout the containing member."6 See Recursion.
- Private functions of a module. A language without nested functions can hide a helper in a module instead. Wikipedia says: "In C, this can be implemented by declaring functions and variables as static to hide them from code"1 outside the file.
- Closures. An inner function that the outer function returns keeps the outer variables. See Closure.
Pitfalls
Assigning to an outer variable in Python
An assignment in the inner function makes a new local variable of the inner function2. Then the read in count += 1 fails:
This code runs but gives a wrong answer on purpose.
def counter():
count = 0
def increment():
count += 1
increment()
return count
try:
print(counter())
except UnboundLocalError as e:
print(type(e).__name__)
UnboundLocalError
Add nonlocal count as the first line of increment. The nonlocal statement "allows encapsulated code to rebind such nonlocal identifiers"3.
An inner function in Bash is global
A Bash function definition inside another function defines the function for the whole shell when the outer function runs13. It can replace a function with the same name:
This code runs but gives a wrong answer on purpose.
helper() {
echo "global helper"
}
outer() {
helper() {
echo "inner helper"
}
helper
}
outer
helper
inner helper
inner helper
After outer runs, the global helper is gone. Give helper functions names with a prefix, such as outer_helper, and do not define functions inside functions.
A Rust inner fn cannot see the outer variables
The Rust reference gives this example11:
fn outer() {
let outer_var = true;
fn inner() { /* outer_var is not in scope here */ }
inner();
}
The reference says that "inner may not access outer_var."11 Use a closure, such as let inner = || outer_var;, or pass the value to the inner fn as a parameter.
Cost
An inner function that uses no outer variables costs the same as a top-level function. An inner function that uses outer variables needs a way to reach them. A classic compiler follows access links between the frames on the stack1. GCC uses another technique when a program takes the address of a nested function: "GCC implements taking the address of a nested function using a technique called trampolines."8 A closure that outlives its call keeps the captured variables alive. In Go, "they survive as long as they are accessible"10. See Stack and heap.
History
"ALGOL 60 function definitions could be nested within one another (a feature introduced by ALGOL 60) with lexical scope."14 Simula 67, Pascal and Ada also have nested procedures1. Wikipedia says nested functions are not supported in C, C++ or Java "as this makes compilers more difficult to implement."1 C# added local functions "starting with C# 7.0"1, and Kotlin and Rust have them1.
References
- Nested function, Wikipedia, the introduction; Attributes; Languages; Implementation
- Execution model, The Python Language Reference, 4.2.1 Binding of names
- Simple statements, The Python Language Reference, 7.13 The nonlocal statement
- Functions, MDN Web Docs JavaScript Guide, Function scopes and closures
- Blocks, Statements, and Patterns, The Java Language Specification, Java SE 25 Edition, 14.2 Blocks; 14.3 Local Class and Interface Declarations
- Local functions, C# Programming Guide, the introduction; Use parameters or capture local state; Choose a local function or lambda expression
- Functions, C reference, cppreference.com, Explanation
- Nested Functions, Using the GNU Compiler Collection (GCC), 6.4 Nested Functions
- Function declaration, C++ reference, cppreference.com, Function definition
- The Go Programming Language Specification, Source file organization; Function literals
- Statements, The Rust Reference, Item declarations
- Closures, The Rust Programming Language, the introduction
- Shell Functions, Bash Reference Manual, 3.3 Shell Functions
- ALGOL 60, Wikipedia, the introduction
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag TFDSQ6 Edit this page History Report an error Markdown