Custom Vars
As mentioned in the vars page, Reflex vars must be JSON serializable.
This means we can support any Python primitive types, as well as lists, dicts, and tuples. However, you can also create more complex var types using dataclasses (recommended), TypedDict, or Pydantic models.
Defining a Type
In this example, we will create a custom var type for storing a transformed piece of text using a dataclass.
Once defined, we can use it as a state var, and reference it from within a component.
Alternative Approaches
Using TypedDict
You can also use TypedDict for defining custom var types:
from typing import TypedDict
class TextEntry(TypedDict):
original_text: str
upper_text: strUsing Pydantic Models
Pydantic models are another option for complex data structures:
from pydantic import BaseModel
class TextEntry(BaseModel):
original_text: str
upper_text: strFor complex data structures, dataclasses are recommended as they provide a clean, type-safe way to define custom var types with good IDE support.