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.


package main

import (

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

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

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