Ross Masters

Justifying my Python annotation habit

I've been refreshing myself on Python annotations - type-hints with additional information attached - after spending some time experimenting with a type-based dependency injection container.

Most times you'll see an annotation, it's something typing, or framework related, but the complexity surrounding those shouldn't scare you off. With inspect.get_annotations() and typing.get_args(), you can easily do your own annotation handling.

As an example, I had a few forms to render using enums for radio & checkbox fields. I needed to pass an input value and a label, but for developer-experience it would have been nicer to use alternate member names in code, than the values passed to the client - I needed a third field. Tuples as enum-values would have been fine, but they're often easy to get the wrong way around.

Annotations to the rescue: