Conceptcore
Binding
Also called binding, name binding, variable binding, bind, rebinding, binding time, early binding, late binding, static binding, dynamic binding, shadowing, unbinding, environment.
A binding is the link between a name and the thing that it names, such as a value, a storage location or a function. Rebinding a name is a different thing from changing the object it names.
- Applies to
- core-languages
Idea
A name in a program is only text. A binding links the name to something: a value, a storage location, a function or a type. Two different operations can then look the same in the code. To rebind a name is to link it to another thing. To mutate is to change the thing that the name is linked to. When two names are bound to one object, a mutation is visible through both names, and a rebinding is not.
# A binding links a name to an object. Assignment makes a binding; it does not copy.
a = [1, 2]
b = a # b is bound to the same list as a
b.append(3) # mutation: the object changes, and both names see it
print(a, a is b)
b = [9] # rebinding: b now names another object, and a is not affected
print(a, b, a is b)
# A function call binds each parameter name to the argument object.
def grow(xs, n):
xs.append(n) # changes the caller's object
n = 0 # rebinds the local name only
return n
k = 4
print(grow(a, k), a, k)
# A closure keeps the binding, not the value it had when the closure was made.
fs = [lambda: i for i in range(3)]
print([f() for f in fs])
fs = [lambda i=i: i for i in range(3)] # a default value is bound when the def runs
print([f() for f in fs])
[1, 2, 3] True
[1, 2, 3] [9] False
0 [1, 2, 3, 4] 4
[2, 2, 2]
[0, 1, 2]
a = [1, 2] binds a to a list, and b = a binds b to the same list. b.append(3) mutates the list, so a shows the change. b = [9] rebinds b, and a is not affected. A call binds each parameter to its argument, so grow can mutate the caller's list but cannot rebind the caller's name k. The last two lines show that a closure keeps the binding of i and reads it when it runs, after the loop has ended.
How it works
Binding and reference. "Name binding is the association of a data or code entity with an identifier", and "An identifier bound to an entity is said to reference that entity"1. The place in the code that makes a binding is a binding occurrence, and the other uses of the name are references1. Scope decides which binding a reference finds. See lexical scope.
Binding constructs. Each language has a fixed set of constructs that bind names. In Python, "The following constructs bind names: formal parameters to functions, class definitions, function definitions, assignment expressions", and also assignment targets, for loop headers, as in with and except, and import2. Declarations such as let, var, const and int x bind names in other languages, and a pattern can bind many names at once.
Rebinding, assignment and mutation. "Rebinding should not be confused with mutation or assignment"1. Languages differ in what a variable is:
- In Python and JavaScript, a variable is a name bound to an object, and assignment rebinds the name.
b = amakes two names for one object. - In C, C++, Go and Rust, a variable is a named storage location, and assignment copies a value into it. A pointer or a reference gives a second way to reach the location. C# calls a
reflocal "an alias to its referent"3. - A
constorfinalbinding cannot be rebound, but the object can still change. MDN says thatconst"creates an immutable reference to a value. It does not mean the value it holds is immutable"4.
Where the binding exists. In Python, "If a name binding operation occurs anywhere within a code block, all uses of the name within the block are treated as references to the current block"2. So a read before the assignment fails with UnboundLocalError, even when a global with the same name exists. In JavaScript, a let binding exists from the start of its block, but code cannot read it before the declaration runs. This gap is the temporal dead zone5.
Closures. A function that uses a name from an enclosing scope keeps the binding, not the value. The Python FAQ explains the result of a loop of lambdas: the variable is read when the lambda is called, not when it is defined6. Languages give a new binding to each iteration of a loop to avoid this problem: let in a JavaScript for loop, foreach in C#, and for in Go7. Java requires that a local variable that a lambda uses is "final or effectively final"8, so the binding can never change.
Static and dynamic binding. Binding also means the choice of which entity a use refers to, made at compile time (static or early binding) or at run time (dynamic or late binding). In Java, a call of an overridden method binds at run time to the class of the object, but for a field "only the type of the Primary expression, not the class of the actual object referred to at run time, is used in determining which field to use"8. See dynamic dispatch.
Linkage. In C, the linker binds names across files. static at file scope gives "internal linkage", so the name is bound only in its file, and extern gives external linkage, so all the files refer to one object9.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Native | |
| Java | Native | |
| C | Native | |
| C# | Native | |
| JavaScript | Native | |
| TypeScript | Native | TypeScript has the let, const and var bindings of JavaScript, and adds readonly properties and the as const assertion, but no example file exists. |
| Go | Native | |
| Rust | Native | |
| Kotlin | Native | Kotlin binds names with val, which cannot be rebound, and var, and a destructuring declaration binds several names at once, but no example file exists because kotlinc is not installed. |
| SQL | Native | A column alias, a table alias and a WITH clause bind names inside a query, and procedural SQL such as PL/pgSQL has DECLARE for variables. No example file exists. |
| Bash | Native | Bash binds a variable with name=value, local makes a binding that is visible in the functions that the function calls, and declare -n makes a name reference. No example file exists. |
| PowerShell | Native | PowerShell binds variables with $name = value, and scope modifiers such as $script:name and $global:name choose the scope of the binding, but no example file exists because pwsh is not installed. |
| HTML | Does not apply | HTML has no names that are bound to values. |
| CSS | Idiom | A custom property such as --gap: 8px binds a name to a value on an element, and var(--gap) reads the binding that the element inherits. |
| Regular expressions | Native | A capture group binds the text that it matches to a number, and a named group binds it to a name that a backreference or the program can use. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | native | assignment, def, import and other statements bind names; global, nonlocal, del |
| JavaScript | native | let, const, var, function declarations; bind for this |
| TypeScript | native | as JavaScript; readonly for properties |
| Java | native | declarations; final; static binding of fields, dynamic binding of methods |
| Kotlin | native | val and var; destructuring declarations |
| C# | native | declarations; ref locals; readonly; virtual and new |
| Go | native | var, const, :=; a new loop variable for each iteration |
| Rust | native | let, let mut, shadowing, patterns, @ |
| C | native | declarations; linkage; block scope |
| C++ | native | references, structured bindings, lambda captures |
| Bash | native | name=value; local; declare -n name references |
| PowerShell | native | $name = value; scope modifiers such as $script: |
| SQL | native | column aliases, WITH names; variables in procedural SQL |
| Regex | native | capture groups bind text to a number or a name |
| HTML | n/a | no names bound to values |
| CSS | idiom | custom properties bind a name to a value on an element |
Every general-purpose language binds names, so the verdict is native. The languages differ in whether a variable is a name for an object or a named location, in which constructs can rebind a name, and in when a binding is made: at compile time, at link time or at run time.
The example files show these differences. Python shows global, nonlocal, the UnboundLocalError rule and del. JavaScript shows const, the temporal dead zone, the loop bindings of var and let, and the binding of this. Java compares the binding of methods, fields and static methods. C# shows a ref local and the captures of for and foreach. Go shows := and shadowing. Rust shows shadowing with a new type, a move and pattern bindings. C shows linkage and block scope. C++ shows a reference that cannot be rebound and a structured binding.
count = 0
def bad():
# An assignment anywhere in a function makes the name local in the whole function.
try:
print(count)
except UnboundLocalError as e:
print(type(e).__name__)
count = 1
def good():
global count # bind the module-level name instead
count += 1
def counter():
n = 0
def inc():
nonlocal n # rebind the name of the enclosing function
n += 1
return n
return inc
bad()
good()
inc = counter()
inc()
print(count, inc())
# import, def, class, for and with all bind names, as assignment does.
import math as m
for i in range(2):
pass
print(m.__name__, i)
# del removes the binding, not the object.
x = y = [1]
del x
print("x" in globals(), y)
UnboundLocalError
1 2
math 1
False [1]
- Verdict: native. An assignment anywhere in a function makes the name local in the whole function, so the read before it raises
UnboundLocalError.globalbinds a name of the module, andnonlocalbinds a name of the enclosing function.import,forand the other binding statements bind names as assignment does.delremoves the binding, and the object stays alive while another name refers to it.
#include <iostream>
#include <map>
#include <string>
int main() {
// A reference is bound once, when it is made. r = b assigns to a; it does not rebind r.
int a = 1, b = 2;
int& r = a;
r = b;
std::cout << a << " " << b << "\n";
// A structured binding gives names to the parts of an object.
std::map<std::string, int> ages{{"ann", 31}, {"bob", 27}};
const char* sep = "";
for (const auto& [name, age] : ages) {
std::cout << sep << name << "=" << age;
sep = " ";
}
std::cout << "\n";
// A lambda captures by value with = and by reference with &.
int k = 1;
auto byValue = [=] { return k; };
auto byRef = [&] { return k; };
k = 5;
std::cout << byValue() << " " << byRef() << "\n";
// A const reference bound to a temporary keeps the temporary alive.
const std::string& s = std::string("tem") + "porary";
std::cout << s << "\n";
}
2 2
ann=31 bob=27
1 5
temporary
- Verdict: native. A reference is bound to one object when it is made, so
r = bassigns toa. A structured binding names the parts of an object. A lambda captures by value with=and by reference with&, so the two lambdas return1and5. Aconstreference bound to a temporary keeps the temporary alive.
import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;
public class Main {
static class Animal {
String kind = "animal";
String sound() { return "..."; }
static String group() { return "Animal"; }
}
static class Dog extends Animal {
String kind = "dog"; // hides the field; it does not override it
@Override String sound() { return "woof"; }
static String group() { return "Dog"; }
}
public static void main(String[] args) {
Animal a = new Dog();
// A method call binds at run time to the method of the object's class.
// A field access and a static method bind at compile time to the declared type.
System.out.println(a.sound() + " " + a.kind + " " + a.group());
// final fixes the binding; the list itself can still change.
final List<Integer> xs = new ArrayList<>();
xs.add(1);
System.out.println(xs);
// A lambda can use a local variable only if the variable is never rebound.
int base = 10;
Supplier<Integer> s = () -> base + 1;
System.out.println(s.get());
// base = 11; // with this line, the lambda does not compile
}
}
woof animal Animal
[1]
11
- Verdict: native. A call of an instance method binds at run time to the method of the class of the object, so
a.sound()calls the method ofDog. A field access and a call of a static method bind at compile time to the declared type, soa.kindreads the field ofAnimal.finalfixes the binding but not the object. A lambda can use a local variable only if the variable is final or effectively final.
#include <stdio.h>
/* static at file scope gives internal linkage: the name is bound only in this file.
A name with external linkage is bound by the linker to one object in the program. */
static int calls = 0;
int next_id(void) {
static int id = 100; /* one object for all calls, initialized once */
calls++;
return id++;
}
int main(void) {
int x = 1;
{
int x = 2; /* a new x in the inner block hides the outer x */
x++;
printf("inner %d\n", x);
}
printf("outer %d\n", x);
/* A pointer gives a second way to reach an object. */
int *p = &x;
*p = 7;
printf("x %d\n", x);
next_id();
next_id();
printf("%d after %d calls\n", next_id(), calls);
return 0;
}
inner 3
outer 1
x 7
102 after 3 calls
- Verdict: native.
staticat file scope gives a name internal linkage, and the linker binds a name with external linkage to one object in the program. An inner block can declare a newxthat hides the outer one. Astaticlocal is one object for all calls. A pointer is a second way to reach an object.
// A ref local binds a name to a storage location, so it is another name for that element.
int[] xs = { 1, 2, 3 };
ref int second = ref xs[1];
second = 20;
Console.WriteLine(string.Join(",", xs));
// A lambda captures the variable, not its value. A for loop has one variable for all
// iterations, and foreach has a new variable for each iteration.
var fromFor = new List<Func<int>>();
for (int i = 0; i < 3; i++) fromFor.Add(() => i);
var fromForeach = new List<Func<int>>();
foreach (int v in new[] { 0, 1, 2 }) fromForeach.Add(() => v);
Console.WriteLine(string.Join(",", fromFor.Select(f => f())) + " " + string.Join(",", fromForeach.Select(f => f())));
// virtual and override bind the call at run time; new hides the method, and the call binds
// at compile time to the declared type.
Base b = new Derived();
Console.WriteLine(b.Virtual() + " " + b.Hidden());
class Base
{
public virtual string Virtual() => "Base.Virtual";
public string Hidden() => "Base.Hidden";
}
class Derived : Base
{
public override string Virtual() => "Derived.Virtual";
public new string Hidden() => "Derived.Hidden";
}
1,20,3
3,3,3 0,1,2
Derived.Virtual Base.Hidden
- Verdict: native. A
reflocal is another name for a storage location, so the assignment changes the array. A lambda captures the variable, so the closures from aforloop all see the last value, and the closures fromforeachsee one value each.overridebinds the call at run time, andnewhides the method, so the call binds to the declared type.
// const fixes the binding, not the object.
const xs = [1, 2];
xs.push(3);
try {
xs = [];
} catch (e) {
console.log(xs, e.name);
}
// A let binding exists from the start of its block, but it cannot be read before
// its declaration runs. This gap is the temporal dead zone.
try {
console.log(later);
} catch (e) {
console.log(e.name);
}
let later = 1;
// var makes one binding for the whole function; let in a for loop makes a new one per iteration.
const withVar = [], withLet = [];
for (var i = 0; i < 3; i++) withVar.push(() => i);
for (let j = 0; j < 3; j++) withLet.push(() => j);
console.log(withVar.map((f) => f()), withLet.map((f) => f()));
// this is bound when the function is called, unless bind fixes it.
const user = { name: "ann", hi() { return this?.name; } };
const loose = user.hi;
const fixed = user.hi.bind(user);
console.log(loose(), fixed());
[ 1, 2, 3 ] TypeError
ReferenceError
[ 3, 3, 3 ] [ 0, 1, 2 ]
undefined ann
- Verdict: native.
constfixes the binding, so the program can change the array but cannot assign a new one. Aletbinding cannot be read before its declaration runs. Avarin aforloop is one binding for all the closures, andletmakes a new binding for each iteration.thisis bound when the function is called, andbindfixes it.
package main
import (
"errors"
"fmt"
"strconv"
)
type counter struct{ n int }
func (c *counter) inc() int { c.n++; return c.n }
func parse(s string) (int, error) {
n, err := strconv.Atoi(s)
if err != nil {
return 0, errors.New("bad number " + strconv.Quote(s))
}
return n, nil
}
func main() {
// := declares new names; with at least one new name on the left, it rebinds the others.
a, err := parse("12")
b, err := parse("x")
fmt.Println(a, b, err)
// := in an inner block makes a new x that shadows the outer x.
x := 1
if a > 0 {
x := 2
x++
}
fmt.Println(x)
// Each iteration of a for loop has its own loop variable.
var fs []func() int
for i := range 3 {
fs = append(fs, func() int { return i })
}
fmt.Println(fs[0](), fs[1](), fs[2]())
// A method value binds the receiver when it is made.
c := &counter{}
next := c.inc
next()
next()
fmt.Println(c.n)
}
12 0 bad number "x"
1
0 1 2
2
- Verdict: native.
:=declares new names, and it can redeclare a name in the same block when at least one name on the left is new. A:=in an inner block declares a new variable that shadows the outer one, so the outerxstays1. Each iteration of aforloop has its own loop variable. A method value binds the receiver when it is made.
fn main() {
// let makes a new binding. A second let with the same name shadows the first,
// and the new binding can have another type.
let n = "42";
let n: i32 = n.parse().unwrap();
println!("{}", n + 1);
// A binding is immutable unless it is declared mut.
let mut total = 0;
for x in [1, 2, 3] {
total += x;
}
println!("{total}");
// let b = a moves a String: the value now belongs to b, and a cannot be used.
let a = String::from("hi");
let b = a;
println!("{b}");
// A pattern binds names to parts of a value; @ binds a name and tests it.
let point = (3, -1);
let (x, y) = point;
let size = match x {
small @ 0..=9 => format!("small {small}"),
other => format!("big {other}"),
};
println!("{x} {y} {size}");
// A move closure copies or moves the value into the closure when the closure is made.
let mut k = 1;
let show = move || k * 10;
k = 5;
println!("{} {}", show(), k);
}
43
6
hi
3 -1 small 3
10 5
- Verdict: native.
letmakes a new binding, and a secondletwith the same name shadows the first, even with another type. A binding is immutable unless it ismut.let b = amoves theString, soacannot be used after it. Patterns bind names to the parts of a value, and@binds a name and tests it. Amoveclosure copieskwhen it is made, so it returns10.
Variations and related ideas
- Binding time. A binding can be fixed when the language is designed (the meaning of
+), when the program is compiled (the type of a variable in C), when it is linked (an external name), when it is loaded, or when it runs (the method for a virtual call). - Lexical and dynamic scope. With lexical scope, a reference finds the binding in the text that encloses it. With dynamic scope, it finds the most recent binding in the calls that are active. Early LISP, Bash
localand Emacs Lisp special variables use dynamic scope. See lexical scope. - Shadowing. An inner declaration with the same name hides the outer binding. Rust uses this often to change the type of a value and keep the name10. Many linters warn about it in other languages.
- Single assignment. In Haskell, Erlang and Elixir patterns, and with
const,finalandval, each binding is made once and never changed. See immutability. - Pattern binding. Destructuring in JavaScript, tuple unpacking in Python, patterns in Rust and structured bindings in C++ bind several names from one value.
Pitfalls
- Aliasing by mistake.
b = awith a list or an object in Python, JavaScript or Java does not copy it. Uselist(a),[...a]or a copy method when a separate object is needed. - Late binding in closures. Closures made in a loop can all see the last value. Use a binding per iteration, or pass the value as a parameter or a default argument.
- Reading a name before the binding.
UnboundLocalErrorin Python andReferenceErrorin JavaScript come from a binding later in the same block. Useglobalornonlocal, or rename the local. - Shadowing an error variable in Go.
x, err := f()in an inner block makes a newerr, and the outererrstays unchanged. The bug passes the compiler. constthat looks deep. Aconstarray or afinallist can still change. Freeze the object or use an immutable type when the content must not change.- Field hiding. A field in a subclass with the same name as a field of its superclass does not override it, and the declared type decides which field a read uses.
Cost
Most bindings cost nothing at run time: the compiler turns a local name into a register or a stack slot. A binding that the program looks up by name, such as a global in Python, costs a hash table lookup. A closure that keeps bindings after its function returns must store them on the heap. Dynamic binding of a method costs an indirect call through a table, which can stop the compiler from inlining the call.
History
The LISP 1.5 manual of 1962 describes how its interpreter binds variables. "The part of the interpreter that binds variables is called apply. When apply encounters a function beginning with LAMBDA, the list of variables is paired with the list of arguments and added to the front of the a-list." To evaluate a variable, the interpreter searches the a-list, and "If a variable has been bound several times, the last or most recent value is used"11. John McCarthy and his co-authors based this on "the Church lambda notation"11. This search gave dynamic scope, and later Lisp dialects moved to lexical scope.
Modern languages separate the binding of a name from the storage of a value. Python describes all of its names as bindings2, C and C++ bind names to objects and use linkage to bind names across files912, and Rust makes each let a new binding that can shadow the last one10. C++ adds references, which are names bound to an existing object: "References are not objects", and a reference that is bound to a temporary can extend its lifetime12. Go changed its for loops so that "Each iteration has its own separate declared variable"7.
References
- Name binding, Wikipedia, Introduction; Rebinding and mutation
- Execution model, The Python Language Reference, 4.2 Naming and binding
- Declaration statements, C# language reference, Reference variables
- const, MDN Web Docs, Description
- let, MDN Web Docs, Temporal dead zone (TDZ)
- Programming FAQ, Python documentation, Why do lambdas defined in a loop with different values all return the same result?
- The Go Programming Language Specification, Short variable declarations; For statements with for clause
- The Java Language Specification, Java SE 25 Edition, Chapter 15, 15.11.1 Field Access Using a Primary; 15.27.2 Lambda Body
- Storage-class specifiers, C reference, cppreference.com, Linkage
- Variables and Mutability, The Rust Programming Language, Shadowing
- LISP 1.5 Programmer's Manual, John McCarthy and others, MIT Press, 1962, Section 2.1, Variables
- Reference declaration, C++ reference, cppreference.com, Rvalue references; Notes
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 QXZRCG Edit this page History Report an error Markdown