Watch keynotes and sessions from MongoDB.live, our virtual developer conference.

Go: why context.TODO() and not context.Background()?

In your documentation of the Go driver there’s always context.TODO() when using a base context.

The description of context.TODO() is

TODO returns a non-nil, empty Context. Code should use context.TODO when it’s unclear which Context to use or it is not yet available (because the surrounding function has not yet been extended to accept a Context parameter).

Are you using context.TODO() for documentation purposes only?

The description of context.Background()

Background returns a non-nil, empty Context. It is never canceled, has no values, and has no deadline. It is typically used by the main function, initialization, and tests, and as the top-level Context for incoming requests.

I’ve been working with Go for the last 7 years and maybe I’ve missed something obvious, but shouldn’t this be mentioned in the documentation?
Or is context.TODO actually the preferred context?

Oh well, not it’s at least official :wink:
Both context.Background() and context.TODO() return the same empty context.

var (

	background = new(emptyCtx)

	todo       = new(emptyCtx)

)


// Background returns a non-nil, empty Context. It is never canceled, has no

// values, and has no deadline. It is typically used by the main function,

// initialization, and tests, and as the top-level Context for incoming

// requests.

func Background() Context {

	return background

}


// TODO returns a non-nil, empty Context. Code should use context.TODO when

// it's unclear which Context to use or it is not yet available (because the

// surrounding function has not yet been extended to accept a Context

// parameter).

func TODO() Context {

	return todo

}

Source: https://golang.org/src/context/context.go

Hi @dalu,

As you mentioned in your response, they are the same context (no timeout/deadline and no associated values). The difference is semantic. I think of context.Background as “I’m deliberately passing in an empty context” and context.TODO as “there should be some other context here, which could be empty, but I’m not sure what the right value is yet so here’s a placeholder”.

We use context.TODO() in the examples embedded in our documentation because the correct value would depend on the calling function, which is usually code from the user’s application. In this case, it’s up to the user to decide what the context should be, which usually depends on things like the maximum time they want the operation to take and whether or not the calling function has a context that it can propagate.

– Divjot

1 Like