Skip to content

Commit 67ad5cc

Browse files
Update custom vars documentation to recommend dataclasses over rx.Base (#1327)
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-authored-by: Alek Petuskey <[email protected]>
1 parent 8149224 commit 67ad5cc

File tree

1 file changed

+36
-3
lines changed

1 file changed

+36
-3
lines changed

docs/vars/custom_vars.md

Lines changed: 36 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
```python exec
22
import reflex as rx
3+
import dataclasses
4+
from typing import TypedDict
35

46
from pcweb.pages.docs import vars
57
```
@@ -8,18 +10,21 @@ from pcweb.pages.docs import vars
810

911
As mentioned in the [vars page]({vars.base_vars.path}), Reflex vars must be JSON serializable.
1012

11-
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 by inheriting from `rx.Base` or decorating them as dataclasses with `@dataclasses.dataclass`.
13+
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.
1214

1315
## Defining a Type
1416

15-
In this example, we will create a custom var type for storing translations.
17+
In this example, we will create a custom var type for storing translations using a dataclass.
1618

1719
Once defined, we can use it as a state var, and reference it from within a component.
1820

1921
```python demo exec
2022
import googletrans
23+
import dataclasses
24+
from typing import TypedDict
2125

22-
class Translation(rx.Base):
26+
@dataclasses.dataclass
27+
class Translation:
2328
original_text: str
2429
translated_text: str
2530

@@ -39,3 +44,31 @@ def translation_example():
3944
rx.text(TranslationState.current_translation.translated_text),
4045
)
4146
```
47+
48+
## Alternative Approaches
49+
50+
### Using TypedDict
51+
52+
You can also use TypedDict for defining custom var types:
53+
54+
```python
55+
from typing import TypedDict
56+
57+
class Translation(TypedDict):
58+
original_text: str
59+
translated_text: str
60+
```
61+
62+
### Using Pydantic Models
63+
64+
Pydantic models are another option for complex data structures:
65+
66+
```python
67+
from pydantic import BaseModel
68+
69+
class Translation(BaseModel):
70+
original_text: str
71+
translated_text: str
72+
```
73+
74+
For complex data structures, dataclasses are recommended as they provide a clean, type-safe way to define custom var types with good IDE support.

0 commit comments

Comments
 (0)