pythonpython-typingliterals

in python 3.8 how to test a field annotated as Literal in a dataclass is valid at run


Given the following example:

from typing import Literal
from dataclasses import dataclass
@dataclass
Class Example:
    answer: Literal['Y', 'N']

x = Example('N')
field = fields(x)[0]

How can I check that the variable field is of type Literal? issubclass(field.type, Literal) doesn't seem to work.

Secondly how can I then get the list ['Y', 'N'] from field.type, so that I could check the value at run time and raise an error when fail = Example('invalid')

pydantic does this but you would have to use their drop in dataclass...


Solution

  • Literal is not a normal type that a python object would have at runtime, it doesn't make sense to check that an object is a Literal

    You can access the annotations for a class using __annotations__, following on from your example:

    >>> Example.__annotations__['answer'].__args__
    ('Y', 'N')