Skip to content
Advertisement

What’s a good pattern for typehinting with `Literal` and then validating at runtime?

Let’s say I have a class:

JavaScript

I would like to maintain the list of viable values, i.e. 'floor', 'ceil', 'square', in only one place. What’s a good recipe for this?

The MyPy docs show some ideas with this suggestion of assert_never but that’s just for MyPy to give an error before runtime, not as a way to maintain a single list of values.

Advertisement

Answer

You can introspect those arguments using the typing module.

JavaScript

You could use a type alias then get the values you want using typing.get_args, so something like:

JavaScript
Advertisement