defer in go is used to run a function later on. Specifically, the specified function will run when the enclosing function returns.

There’s no clean equivalent to this in Python that I’ve found.

The quintessential example is closing a file handle as your program exits.

Example

package main

import (
	"fmt"
	"os"
)

func main() {
	file := createFile("/tmp/testingdefer.txt")
	defer closeFile(file)
	writeFile(file)
}

func createFile(path string) (file *os.File) {
	fmt.Println("creating file: ", path)
	file, _ = os.Create(path) // skipping error handling for brevity
	return
}

func writeFile(file *os.File) {
	fmt.Println("writing file")
	fmt.Fprintln(file, "here is some data for you!")
}

func closeFile(file *os.File) {
	fmt.Println("closing file")
	file.Close() // skipping error handling for brevity
}