Skip to content

Updating type annotations to support string literals #1579

@MaximSrour

Description

@MaximSrour

Is your feature request related to a problem? Please describe.
Using the ormar.String with a string literal type hint causes a type error, as the ormar string is more permissive than the literal:

mode: Literal["user", "manager", "admin"] = ormar.String(max_length=32)
# results in: Type "str" is not assignable to declared type "Literal['user', 'manager', 'admin']"

Describe the solution you'd like
Ideally, either a new model field, ormar.Literal, or the ability to provide valid values to the ormar.String field, thus removing the type error.

Describe alternatives you've considered
I have tried using enums before, however they can be tedious to work with in Postgres due to the addition of new values requiring a hefty migration (which can be very slow to run against large datasets). Using a varchar results in it being more flexible, but it lacks this degree of type safety.

Another option is to use an ormar string with a string type hint, then cast the value to the literal once it's confirmed to be a valid value, however this pushes a lot of boilerplate into the domain code. Having the model field typed as a literal immediately means it can be consumed from anywhere and be guaranteed to be correct.

Additional context
Nil.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions