← Writing

Dataclass field metadata: Pythonic equivalence of Go struct tag

1. What’s a Go struct tag?

I’ve been writing some Go lately, and there’s one little language feature I immediately fell in love with: struct tags.

A struct tag is just a raw string literal glued to the end of a struct field. Go itself doesn’t care what’s inside it — you read it at runtime with reflection and turn it into whatever behaviour you want. Looks like this:

type MyAwesomeGoServiceConfig struct {
  Host   string `envconfig:"SERVICE_HOST" another_random_tag:"amazing"`
  Port   string `envconfig:"SERVICE_PORT" this_is_seriously_cool:"agree"`
}

Uncharacteristically upbeat field names aside, that is 100% valid Go:

func main() {
  s := MyAwesomeGoServiceConfig{Host:"blog.limdauto.me", Port:"8080"}
  fmt.Printf("%+v\n", s)
}

// go run main.go
// {Host:blog.limdauto.me Port:8080}

On its own, the tag just sits there. The fun starts when a library reads it. Take envconfig, which looks for envconfig:"..." tags and fills your struct straight from environment variables:

func main() {
  var s MyAwesomeGoServiceConfig
  envconfig.Process("example", &s)
  fmt.Printf("%+v\n", s)
}

// go run main.go
// {Host: Port:}
// SERVICE_HOST=blog.limdauto.me SERVICE_PORT=8080 go run main.go
// {Host:blog.limdauto.me Port:8080}

2. Why should a Python dev care?

Browse Go’s well-known struct tags and you’ll see why people love them. The json tag, for example, is how Go maps JSON straight into typed structs and back.

I don’t know about you, but years of passing raw dicts around in Python have left permanent scars. Data can travel over the wire as JSON or YAML or whatever it wants, but the second it crosses into my code, I want a real object with a real schema. My friend Max once summed up his entire software engineering career as “loading JSON from one place and writing it to another.” Honestly, no notes.

Say you’re building a dating app for Star Wars characters (why not). You hit the Star Wars API and want to keep the fields you care about while ignoring the rest — who cares what species Luke is, it’s 2019! Wouldn’t it be nice to write something like this in Python?

from datetime import datetime

class StarWarsCharacter:
    name: str
    dob: datetime, tags={"json": "birth_year"}
    eye_color: str
    gender: str
    hair_color: str
    height: str
    mass: int
    skin_color: str

    # skip during JSON parsing, but we still need it for online dating
    mbti_personality_type: str, tags={"json": "-"}

import requests
luke = requests.get('https://swapi.dev/api/people/1/').as_(StarWarsCharacter)

(Confession: I have never actually watched Star Wars. Please don’t send hate mail.)

3. Plot twist: Python already has this

I was about to burn a weekend porting Go struct tags to Python when I discovered Python 3.7+ already shipped them. They’re just tucked away in the metadata parameter of dataclasses.field:

from dataclasses import dataclass, field

@dataclass
class MyAwesomeServiceConfig:
    Host: str = field(metadata={"envconfig": "SERVICE_HOST"})
    Port: str = field(metadata={"envconfig": "SERVICE_PORT"})

Reading those tags back out takes five lines:

import os
from dataclasses import fields

def process(config_class):
    config_data = {}
    for f in fields(config_class):
        config_data[f.name] = os.getenv(f.metadata['envconfig'])
    return config_class(**config_data)

Okay, that version is way too naive — it crashes on untagged fields, ignores defaults, and hands you back port as a string. Add a handful of lines and a tiny env() helper to hide the field(metadata=...) boilerplate, and it starts feeling genuinely nice:

import os
from dataclasses import MISSING, dataclass, field, fields

def env(name, **kwargs):
    return field(metadata={"envconfig": name}, **kwargs)

def process(config_class, environ=os.environ):
    values = {}
    for f in fields(config_class):
        name = f.metadata.get("envconfig")
        if name is None:
            continue  # untagged fields keep their defaults
        if name in environ:
            values[f.name] = f.type(environ[name])
        elif f.default is MISSING and f.default_factory is MISSING:
            raise KeyError(f"{name} is required")
    return config_class(**values)

@dataclass
class ServiceConfig:
    host: str = env("SERVICE_HOST")
    port: int = env("SERVICE_PORT", default=8080)
    debug: bool = env("SERVICE_DEBUG", default=False)

Let’s try it:

process(ServiceConfig, {"SERVICE_HOST": "limdauto.me"})
# ServiceConfig(host='limdauto.me', port=8080, debug=False)

process(ServiceConfig, {"SERVICE_HOST": "limdauto.me", "SERVICE_PORT": "9000"})
# ServiceConfig(host='limdauto.me', port=9000, debug=False)

process(ServiceConfig, {})
# KeyError: 'SERVICE_HOST is required'

f.type is literally the type annotation object itself, so calling f.type("9000") turns "9000" straight into 9000 for free.

I was feeling pretty smug about this — right up until I tried turning debug off:

process(ServiceConfig, {"SERVICE_HOST": "limdauto.me", "SERVICE_DEBUG": "false"})
# ServiceConfig(host='limdauto.me', port=8080, debug=True)

Right. bool("false") is True in Python, because any non-empty string is truthy. Of course it is. Handling booleans, lists, and bad inputs properly is basically the gap between a blog post and an actual library — so please don’t copy-paste this into production 😅

4. Luke’s dating profile, for real

I left Luke’s dating profile as pseudo-code earlier, which is no way to find love. Go’s json tag does two handy things: rename a field, or skip it with "-". We can build both in seven lines:

def from_json(cls, data):
    values = {}
    for f in fields(cls):
        key = f.metadata.get("json", f.name)
        if key != "-":
            values[f.name] = data[key]
    return cls(**values)

@dataclass
class StarWarsCharacter:
    name: str
    eye_color: str
    hair_color: str
    height: str
    dob: str = field(metadata={"json": "birth_year"})
    mbti_personality_type: str = field(default="unknown", metadata={"json": "-"})

# Trimmed response from https://swapi.dev/api/people/1/
luke = {
    "name": "Luke Skywalker",
    "height": "172",
    "mass": "77",
    "hair_color": "blond",
    "skin_color": "fair",
    "eye_color": "blue",
    "birth_year": "19BBY",
    "gender": "male",
}

from_json(StarWarsCharacter, luke)
# StarWarsCharacter(name='Luke Skywalker', eye_color='blue', hair_color='blond',
#                   height='172', dob='19BBY', mbti_personality_type='unknown')

birth_year landed in dob, mass and skin_color got dropped, and mbti_personality_type stayed out of the JSON completely. And yes, I downgraded dob from datetime to str — I have no idea how to parse "19BBY" into a Python datetime, and I doubt datetime does either.

5. Annotated: struct tags everywhere

Since Python 3.9, there’s an even cleaner way to do this: typing.Annotated. Instead of wrapping your field in field(metadata=...), you hang arbitrary Python objects straight onto the type hint:

from typing import Annotated, get_type_hints

@dataclass(frozen=True)
class Env:
    name: str

@dataclass
class ServiceConfig:
    host: Annotated[str, Env("SERVICE_HOST")]
    port: Annotated[int, Env("SERVICE_PORT")] = 8080

hints = get_type_hints(ServiceConfig, include_extras=True)
hints["port"].__origin__    # <class 'int'>
hints["port"].__metadata__  # (Env(name='SERVICE_PORT'),)

This feels much closer to Go’s struct tags: the tag sits right beside the type, there’s no field() wrapper, and plain default values just work. Better yet, it works places Go struct tags can’t touch — like function parameters:

def connect(
    host: Annotated[str, Env("SERVICE_HOST")],
    port: Annotated[int, Env("SERVICE_PORT")] = 8080,
): ...

get_type_hints(connect, include_extras=True)["host"].__metadata__
# (Env(name='SERVICE_HOST'),)

If you’ve ever written q: Annotated[str, Query(max_length=50)] in FastAPI or Annotated[int, Field(gt=0)] in Pydantic, you’ve been using Python’s version of struct tags all along.

Here’s the cheat sheet:

Go struct tag Dataclass metadata Annotated
The tag is a string a read-only mapping any Python object
Goes on struct fields dataclass fields any type hint
Read via reflect fields() get_type_hints()
Typo in tag silently ignored silently ignored instant NameError
Since Go 1.0 Python 3.7 Python 3.9

The typo row is my favourite. In Go, envconifg:"SERVICE_HOST" compiles with a smile and quietly does nothing — enjoy your afternoon of debugging. With Annotated, misspelling Env crashes the moment you import the file.

Dataclass metadata still has a sweet spot, though: if you’re already in a dataclass and only your own code reads the tags, it’s one import and zero extra wrapper classes. Just namespace your keys cleanly, since the mapping is shared with any other library inspecting the field.

6. Two libraries worth a look

While poking around for this post, I ran into two neat Python libraries in the same space:

  • jsons (mind the s) — lets you load and dump dataclasses directly (jsons.load(some_dict, SomeClass)). Doesn’t lean on field metadata, but the API is super clean.
  • marshmallow_dataclass — reads dataclass field metadata to generate marshmallow schemas automatically. Exact proof of how far this pattern can go.