forked from lukasmasuch/streamlit-pydantic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathunion_field_discriminator.py
49 lines (32 loc) · 1.17 KB
/
union_field_discriminator.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
from typing import Literal, Optional, Union
import streamlit as st
from pydantic import BaseModel, Field
import st_pydantic as sp
class PostalAddress(BaseModel):
contact_type: Literal["postal"]
street: str
city: str
house: int
class EmailAddress(BaseModel):
contact_type: Literal["email"]
email: str
send_news: bool
class ContactMethod(BaseModel):
contact: Optional[Union[PostalAddress, EmailAddress]] = Field(..., discriminator="contact_type")
text: str
from_model_tab, from_instance_tab = st.tabs(["Form inputs from model", "Form inputs from instance"])
with from_model_tab:
input_data = sp.pydantic_input(key="union_input", model=ContactMethod)
if input_data:
st.json(input_data)
with from_instance_tab:
instance = ContactMethod(
contact=EmailAddress(contact_type="email", email="[email protected]", send_news=True),
text="instance text",
)
instance_input_data = sp.pydantic_input(key="union_input_instance", model=instance)
if instance_input_data:
st.json(instance_input_data)
st.markdown("---")
with st.expander("Session State", expanded=False):
st.write(st.session_state)