Comment by haiku2077

5 days ago

> Context system: Go provides a capable copy-on-write data bag that explicitly flows through the code execution path, similar to contextvars in Python or .NET's execution context. Its explicit nature greatly simplifies things for AI agents. If the agent needs to pass stuff to any call site, it knows how to do it.

I believe this is considered a bad practice: the general attitude is that the only sane use case for values in context.Context is tracing data, and all other data should he explicitly passed via arguments.

Agreed on all points.

The only place I’ve encountered this pattern is in chromedp, the go wrapper for the chrome headless browser driver. Its API… isn’t good.

Most methods you use are package globals that take a context.Context as a first parameter. But you have to understand that this context is a _special_ one: you can’t pass any old context like context.Background(), you must pass a context you got from one of the factory methods.

If you want to specify a timeout, you use context.WithTimeout. Clever I guess, but that’s the only setting that works like that.

It’s essentially a void*.

I'm really not an expect in Go, but the data that I'm passing at the moment via context is the type of data which is commonly placed there by libraries I use: database connections, config, rate limiters, cache backends etc. Does not seem particularly bad to me at least.

  • If you use context.Context for this you give up a lot of type safety and generally make your data passing opaque.

    It's totally fine to put multiple values into a different data bag type that has explicit, typed fields. For example, the Echo framework has its own strongly typed and extensible Context interface for request scoped data: https://pkg.go.dev/github.com/labstack/echo#Context

    • > If you use context.Context for this you give up a lot of type safety and generally make your data passing opaque.

      The data passing maybe, not sure how you lose type safety. The value comes from the context with the right type just fine. The stuff that I'm attaching to the context are effectively globals just that this way you can enable proper isolation in tests and else.

      From my limited experience with echo, the context there is not at all the same thing.

      3 replies →