rio-labs / rio

WebApps in pure Python. No JavaScript, HTML and CSS needed
https://rio.dev
Apache License 2.0
1.32k stars 38 forks source link

Replace string literals with ENUM types #39

Closed drodenkirchen closed 4 months ago

drodenkirchen commented 4 months ago

DO NOT MERGE YET - NOT FINAL

What does it do?

This pull request replaces the existing Literal string type annotations with an Enum type. This change is aimed at improving the maintainability, readability, and robustness of the codebase.

Why is it needed?

Previously, the codebase used Literal string type annotations to define a set of valid string values for specific variables and function parameters. This approach, while functional, has several limitations that can be addressed by using Enum types:

Improved Readability:

Enums provide a clear, self-documenting way to represent a set of constant values. By using descriptive names for enum members, the code becomes more understandable and easier to read.

Type Safety:

Enums enforce type safety more rigorously than Literal strings. They ensure that only predefined values can be assigned, reducing the risk of runtime errors caused by invalid string literals.

Enhanced Maintainability:

Centralizing the definition of valid values in an Enum makes it easier to manage and update the set of possible values. Changes to the valid values need to be made in only one place, minimizing the risk of inconsistencies.

Auto-Completion and IDE Support:

Modern IDEs provide better support for enums, offering auto-completion and inline documentation, which can speed up development and reduce errors.

How to test it?

Just install it and run any predefined template. Nothing should've changed. But I have not yet understood how the translation of width/height values into JS/HTML/CSS work !

Example

Previously:

    # [...]
    width: float | Literal["natural", "grow"] = "natural"
    height: float | Literal["natural", "grow"] = "natural"

Now:

    # [...]
    width: float | ExpandStrategy = ExpandStrategy.NATURAL
    height: float | ExpandStrategy = ExpandStrategy.NATURAL
mad-moo commented 4 months ago

Supporting both literals and enum would be nice, since this would allow all developers to go with their own preference. However, as discussed on discord, this comes with a few issues.

Replacing the type annotations with enums would be flagged by type checkers, effectively disallowing the use of literals, even if we were to internally convert everything to strings. StrEnums could possibly alleviate this, but aren't supported in 3.10, which Rio supports.

I'm closing this for now