We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
st.radio with DataFrame fails on rerun
### Summary

When you pass a DataFrame as the options in an st.radio, every rerun throws an error (but the first run works).

### Steps to reproduce

Code snippet:

```
import streamlit as st
import pandas as pd

df = pd.DataFrame({'foo': ['one', 'two']})
st.radio('Foo', df)
```

1. Run the code above.
2. Press "R" to rerun the code above.

**Expected behavior:**

The rerun works, just like the first run.

**Actual behavior:**

The app hangs (stays in running state forever) and shows the error below in the terminal:

```
Exception in thread ScriptRunner.scriptThread:
Traceback (most recent call last):
  File "/usr/local/Cellar/python@3.9/3.9.5/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 954, in _bootstrap_inner
    self.run()
  File "/usr/local/Cellar/python@3.9/3.9.5/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 892, in run
    self._target(*self._args, **self._kwargs)
  File "/Users/[HIDDEN]/.venv/lib/python3.9/site-packages/streamlit/script_runner.py", line 210, in _process_request_queue
    widget_states = self._session_state.as_widget_states()
  File "/Users/[HIDDEN]/.venv/lib/python3.9/site-packages/streamlit/state/session_state.py", line 560, in as_widget_states
    return self._new_widget_state.as_widget_states()
  File "/Users/[HIDDEN]/.venv/lib/python3.9/site-packages/streamlit/state/session_state.py", line 211, in as_widget_states
    states = [
  File "/Users/[HIDDEN]/.venv/lib/python3.9/site-packages/streamlit/state/session_state.py", line 214, in <listcomp>
    if self.get_serialized(widget_id)
  File "/Users/[HIDDEN]/.venv/lib/python3.9/site-packages/streamlit/state/session_state.py", line 190, in get_serialized
    serialized = metadata.serializer(item.value)
  File "/Users/[HIDDEN]/.venv/lib/python3.9/site-packages/streamlit/elements/radio.py", line 136, in serialize_radio
    return index_(options, v)
  File "/Users/[HIDDEN]/.venv/lib/python3.9/site-packages/streamlit/util.py", line 129, in index_
    raise ValueError("{} is not in iterable".format(str(x)))
ValueError: one is not in iterable
```


### Is this a regression?

yes 

Previous known working version = 0.84.0

### Debug info

- Streamlit version: 1.4.0
- Python version: 3.9.5

### Additional information

A meta-bug related to this: I'm not sure why this error is thrown in the terminal rather than inside the Streamlit app. Previously, our goal was to have _every_ error appear in the app, so you never had to check the terminal. It would be great to see if some code change unexpectedly changed this behavior.

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `e2e/scripts/st_radio.py`
Content:
```
1 # Copyright 2018-2022 Streamlit Inc.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 #    http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 
15 import streamlit as st
16 
17 options = ("female", "male")
18 i1 = st.radio("radio 1", options, 1)
19 st.write("value 1:", i1)
20 
21 i2 = st.radio("radio 2", options, 0, format_func=lambda x: x.capitalize())
22 st.write("value 2:", i2)
23 
24 i3 = st.radio("radio 3", [])
25 st.write("value 3:", i3)
26 
27 i4 = st.radio("radio 4", options, disabled=True)
28 st.write("value 4:", i4)
29 
30 i5 = st.radio("radio 5", options, horizontal=True)
31 st.write("value 5:", i5)
32 
33 if st._is_running_with_streamlit:
34 
35     def on_change():
36         st.session_state.radio_changed = True
37 
38     st.radio("radio 6", options, 1, key="radio6", on_change=on_change)
39     st.write("value 6:", st.session_state.radio6)
40     st.write("radio changed:", "radio_changed" in st.session_state)
41
```

Path: `lib/streamlit/elements/radio.py`
Content:
```
1 # Copyright 2018-2022 Streamlit Inc.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 #    http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 
15 from textwrap import dedent
16 from typing import Any, Callable, Optional, cast
17 
18 import streamlit
19 from streamlit.errors import StreamlitAPIException
20 from streamlit.proto.Radio_pb2 import Radio as RadioProto
21 from streamlit.scriptrunner import ScriptRunContext, get_script_run_ctx
22 from streamlit.state import (
23     register_widget,
24     WidgetArgs,
25     WidgetCallback,
26     WidgetKwargs,
27 )
28 from streamlit.type_util import Key, OptionSequence, ensure_indexable, to_key
29 from streamlit.util import index_
30 from .form import current_form_id
31 from .utils import check_callback_rules, check_session_state_rules
32 
33 
34 class RadioMixin:
35     def radio(
36         self,
37         label: str,
38         options: OptionSequence,
39         index: int = 0,
40         format_func: Callable[[Any], Any] = str,
41         key: Optional[Key] = None,
42         help: Optional[str] = None,
43         on_change: Optional[WidgetCallback] = None,
44         args: Optional[WidgetArgs] = None,
45         kwargs: Optional[WidgetKwargs] = None,
46         *,  # keyword-only args:
47         disabled: bool = False,
48         horizontal: bool = False,
49     ) -> Any:
50         """Display a radio button widget.
51 
52         Parameters
53         ----------
54         label : str
55             A short label explaining to the user what this radio group is for.
56         options : Sequence, numpy.ndarray, pandas.Series, pandas.DataFrame, or pandas.Index
57             Labels for the radio options. This will be cast to str internally
58             by default. For pandas.DataFrame, the first column is selected.
59         index : int
60             The index of the preselected option on first render.
61         format_func : function
62             Function to modify the display of radio options. It receives
63             the raw option as an argument and should output the label to be
64             shown for that option. This has no impact on the return value of
65             the radio.
66         key : str or int
67             An optional string or integer to use as the unique key for the widget.
68             If this is omitted, a key will be generated for the widget
69             based on its content. Multiple widgets of the same type may
70             not share the same key.
71         help : str
72             An optional tooltip that gets displayed next to the radio.
73         on_change : callable
74             An optional callback invoked when this radio's value changes.
75         args : tuple
76             An optional tuple of args to pass to the callback.
77         kwargs : dict
78             An optional dict of kwargs to pass to the callback.
79         disabled : bool
80             An optional boolean, which disables the radio button if set to
81             True. The default is False. This argument can only be supplied by
82             keyword.
83         horizontal : bool
84             An optional boolean, which orients the radio group horizontally.
85             The default is false (vertical buttons). This argument can only
86             be supplied by keyword.
87 
88         Returns
89         -------
90         any
91             The selected option.
92 
93         Example
94         -------
95         >>> genre = st.radio(
96         ...     "What\'s your favorite movie genre",
97         ...     ('Comedy', 'Drama', 'Documentary'))
98         >>>
99         >>> if genre == 'Comedy':
100         ...     st.write('You selected comedy.')
101         ... else:
102         ...     st.write("You didn\'t select comedy.")
103 
104         .. output::
105            https://doc-radio.streamlitapp.com/
106            height: 260px
107 
108         """
109         ctx = get_script_run_ctx()
110         return self._radio(
111             label=label,
112             options=options,
113             index=index,
114             format_func=format_func,
115             key=key,
116             help=help,
117             on_change=on_change,
118             args=args,
119             kwargs=kwargs,
120             disabled=disabled,
121             horizontal=horizontal,
122             ctx=ctx,
123         )
124 
125     def _radio(
126         self,
127         label: str,
128         options: OptionSequence,
129         index: int = 0,
130         format_func: Callable[[Any], Any] = str,
131         key: Optional[Key] = None,
132         help: Optional[str] = None,
133         on_change: Optional[WidgetCallback] = None,
134         args: Optional[WidgetArgs] = None,
135         kwargs: Optional[WidgetKwargs] = None,
136         *,  # keyword-only args:
137         disabled: bool = False,
138         horizontal: bool = False,
139         ctx: Optional[ScriptRunContext],
140     ) -> Any:
141         key = to_key(key)
142         check_callback_rules(self.dg, on_change)
143         check_session_state_rules(default_value=None if index == 0 else index, key=key)
144 
145         opt = ensure_indexable(options)
146 
147         if not isinstance(index, int):
148             raise StreamlitAPIException(
149                 "Radio Value has invalid type: %s" % type(index).__name__
150             )
151 
152         if len(opt) > 0 and not 0 <= index < len(opt):
153             raise StreamlitAPIException(
154                 "Radio index must be between 0 and length of options"
155             )
156 
157         radio_proto = RadioProto()
158         radio_proto.label = label
159         radio_proto.default = index
160         radio_proto.options[:] = [str(format_func(option)) for option in opt]
161         radio_proto.form_id = current_form_id(self.dg)
162         radio_proto.horizontal = horizontal
163         if help is not None:
164             radio_proto.help = dedent(help)
165 
166         def deserialize_radio(ui_value, widget_id=""):
167             idx = ui_value if ui_value is not None else index
168 
169             return opt[idx] if len(opt) > 0 and opt[idx] is not None else None
170 
171         def serialize_radio(v):
172             if len(options) == 0:
173                 return 0
174             return index_(options, v)
175 
176         widget_state = register_widget(
177             "radio",
178             radio_proto,
179             user_key=key,
180             on_change_handler=on_change,
181             args=args,
182             kwargs=kwargs,
183             deserializer=deserialize_radio,
184             serializer=serialize_radio,
185             ctx=ctx,
186         )
187 
188         # This needs to be done after register_widget because we don't want
189         # the following proto fields to affect a widget's ID.
190         radio_proto.disabled = disabled
191         if widget_state.value_changed:
192             radio_proto.value = serialize_radio(widget_state.value)
193             radio_proto.set_value = True
194 
195         self.dg._enqueue("radio", radio_proto)
196         return widget_state.value
197 
198     @property
199     def dg(self) -> "streamlit.delta_generator.DeltaGenerator":
200         """Get our DeltaGenerator."""
201         return cast("streamlit.delta_generator.DeltaGenerator", self)
202
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/e2e/scripts/st_radio.py b/e2e/scripts/st_radio.py
--- a/e2e/scripts/st_radio.py
+++ b/e2e/scripts/st_radio.py
@@ -12,6 +12,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
+import pandas as pd
 import streamlit as st
 
 options = ("female", "male")
@@ -30,11 +31,15 @@
 i5 = st.radio("radio 5", options, horizontal=True)
 st.write("value 5:", i5)
 
+i6 = st.radio("radio 6", pd.DataFrame({"foo": list(options)}))
+st.write("value 6:", i6)
+
+
 if st._is_running_with_streamlit:
 
     def on_change():
         st.session_state.radio_changed = True
 
-    st.radio("radio 6", options, 1, key="radio6", on_change=on_change)
-    st.write("value 6:", st.session_state.radio6)
+    st.radio("radio 7", options, 1, key="radio7", on_change=on_change)
+    st.write("value 7:", st.session_state.radio7)
     st.write("radio changed:", "radio_changed" in st.session_state)
diff --git a/lib/streamlit/elements/radio.py b/lib/streamlit/elements/radio.py
--- a/lib/streamlit/elements/radio.py
+++ b/lib/streamlit/elements/radio.py
@@ -169,9 +169,9 @@
             return opt[idx] if len(opt) > 0 and opt[idx] is not None else None
 
         def serialize_radio(v):
-            if len(options) == 0:
+            if len(opt) == 0:
                 return 0
-            return index_(options, v)
+            return index_(opt, v)
 
         widget_state = register_widget(
             "radio",

{"golden_diff": "diff --git a/e2e/scripts/st_radio.py b/e2e/scripts/st_radio.py\n--- a/e2e/scripts/st_radio.py\n+++ b/e2e/scripts/st_radio.py\n@@ -12,6 +12,7 @@\n # See the License for the specific language governing permissions and\n # limitations under the License.\n \n+import pandas as pd\n import streamlit as st\n \n options = (\"female\", \"male\")\n@@ -30,11 +31,15 @@\n i5 = st.radio(\"radio 5\", options, horizontal=True)\n st.write(\"value 5:\", i5)\n \n+i6 = st.radio(\"radio 6\", pd.DataFrame({\"foo\": list(options)}))\n+st.write(\"value 6:\", i6)\n+\n+\n if st._is_running_with_streamlit:\n \n     def on_change():\n         st.session_state.radio_changed = True\n \n-    st.radio(\"radio 6\", options, 1, key=\"radio6\", on_change=on_change)\n-    st.write(\"value 6:\", st.session_state.radio6)\n+    st.radio(\"radio 7\", options, 1, key=\"radio7\", on_change=on_change)\n+    st.write(\"value 7:\", st.session_state.radio7)\n     st.write(\"radio changed:\", \"radio_changed\" in st.session_state)\ndiff --git a/lib/streamlit/elements/radio.py b/lib/streamlit/elements/radio.py\n--- a/lib/streamlit/elements/radio.py\n+++ b/lib/streamlit/elements/radio.py\n@@ -169,9 +169,9 @@\n             return opt[idx] if len(opt) > 0 and opt[idx] is not None else None\n \n         def serialize_radio(v):\n-            if len(options) == 0:\n+            if len(opt) == 0:\n                 return 0\n-            return index_(options, v)\n+            return index_(opt, v)\n \n         widget_state = register_widget(\n             \"radio\",\n", "issue": "st.radio with DataFrame fails on rerun\n### Summary\r\n\r\nWhen you pass a DataFrame as the options in an st.radio, every rerun throws an error (but the first run works).\r\n\r\n### Steps to reproduce\r\n\r\nCode snippet:\r\n\r\n```\r\nimport streamlit as st\r\nimport pandas as pd\r\n\r\ndf = pd.DataFrame({'foo': ['one', 'two']})\r\nst.radio('Foo', df)\r\n```\r\n\r\n1. Run the code above.\r\n2. Press \"R\" to rerun the code above.\r\n\r\n**Expected behavior:**\r\n\r\nThe rerun works, just like the first run.\r\n\r\n**Actual behavior:**\r\n\r\nThe app hangs (stays in running state forever) and shows the error below in the terminal:\r\n\r\n```\r\nException in thread ScriptRunner.scriptThread:\r\nTraceback (most recent call last):\r\n  File \"/usr/local/Cellar/python@3.9/3.9.5/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py\", line 954, in _bootstrap_inner\r\n    self.run()\r\n  File \"/usr/local/Cellar/python@3.9/3.9.5/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py\", line 892, in run\r\n    self._target(*self._args, **self._kwargs)\r\n  File \"/Users/[HIDDEN]/.venv/lib/python3.9/site-packages/streamlit/script_runner.py\", line 210, in _process_request_queue\r\n    widget_states = self._session_state.as_widget_states()\r\n  File \"/Users/[HIDDEN]/.venv/lib/python3.9/site-packages/streamlit/state/session_state.py\", line 560, in as_widget_states\r\n    return self._new_widget_state.as_widget_states()\r\n  File \"/Users/[HIDDEN]/.venv/lib/python3.9/site-packages/streamlit/state/session_state.py\", line 211, in as_widget_states\r\n    states = [\r\n  File \"/Users/[HIDDEN]/.venv/lib/python3.9/site-packages/streamlit/state/session_state.py\", line 214, in <listcomp>\r\n    if self.get_serialized(widget_id)\r\n  File \"/Users/[HIDDEN]/.venv/lib/python3.9/site-packages/streamlit/state/session_state.py\", line 190, in get_serialized\r\n    serialized = metadata.serializer(item.value)\r\n  File \"/Users/[HIDDEN]/.venv/lib/python3.9/site-packages/streamlit/elements/radio.py\", line 136, in serialize_radio\r\n    return index_(options, v)\r\n  File \"/Users/[HIDDEN]/.venv/lib/python3.9/site-packages/streamlit/util.py\", line 129, in index_\r\n    raise ValueError(\"{} is not in iterable\".format(str(x)))\r\nValueError: one is not in iterable\r\n```\r\n\r\n\r\n### Is this a regression?\r\n\r\nyes \r\n\r\nPrevious known working version = 0.84.0\r\n\r\n### Debug info\r\n\r\n- Streamlit version: 1.4.0\r\n- Python version: 3.9.5\r\n\r\n### Additional information\r\n\r\nA meta-bug related to this: I'm not sure why this error is thrown in the terminal rather than inside the Streamlit app. Previously, our goal was to have _every_ error appear in the app, so you never had to check the terminal. It would be great to see if some code change unexpectedly changed this behavior.\n", "before_files": [{"content": "# Copyright 2018-2022 Streamlit Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#    http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport streamlit as st\n\noptions = (\"female\", \"male\")\ni1 = st.radio(\"radio 1\", options, 1)\nst.write(\"value 1:\", i1)\n\ni2 = st.radio(\"radio 2\", options, 0, format_func=lambda x: x.capitalize())\nst.write(\"value 2:\", i2)\n\ni3 = st.radio(\"radio 3\", [])\nst.write(\"value 3:\", i3)\n\ni4 = st.radio(\"radio 4\", options, disabled=True)\nst.write(\"value 4:\", i4)\n\ni5 = st.radio(\"radio 5\", options, horizontal=True)\nst.write(\"value 5:\", i5)\n\nif st._is_running_with_streamlit:\n\n    def on_change():\n        st.session_state.radio_changed = True\n\n    st.radio(\"radio 6\", options, 1, key=\"radio6\", on_change=on_change)\n    st.write(\"value 6:\", st.session_state.radio6)\n    st.write(\"radio changed:\", \"radio_changed\" in st.session_state)\n", "path": "e2e/scripts/st_radio.py"}, {"content": "# Copyright 2018-2022 Streamlit Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#    http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom textwrap import dedent\nfrom typing import Any, Callable, Optional, cast\n\nimport streamlit\nfrom streamlit.errors import StreamlitAPIException\nfrom streamlit.proto.Radio_pb2 import Radio as RadioProto\nfrom streamlit.scriptrunner import ScriptRunContext, get_script_run_ctx\nfrom streamlit.state import (\n    register_widget,\n    WidgetArgs,\n    WidgetCallback,\n    WidgetKwargs,\n)\nfrom streamlit.type_util import Key, OptionSequence, ensure_indexable, to_key\nfrom streamlit.util import index_\nfrom .form import current_form_id\nfrom .utils import check_callback_rules, check_session_state_rules\n\n\nclass RadioMixin:\n    def radio(\n        self,\n        label: str,\n        options: OptionSequence,\n        index: int = 0,\n        format_func: Callable[[Any], Any] = str,\n        key: Optional[Key] = None,\n        help: Optional[str] = None,\n        on_change: Optional[WidgetCallback] = None,\n        args: Optional[WidgetArgs] = None,\n        kwargs: Optional[WidgetKwargs] = None,\n        *,  # keyword-only args:\n        disabled: bool = False,\n        horizontal: bool = False,\n    ) -> Any:\n        \"\"\"Display a radio button widget.\n\n        Parameters\n        ----------\n        label : str\n            A short label explaining to the user what this radio group is for.\n        options : Sequence, numpy.ndarray, pandas.Series, pandas.DataFrame, or pandas.Index\n            Labels for the radio options. This will be cast to str internally\n            by default. For pandas.DataFrame, the first column is selected.\n        index : int\n            The index of the preselected option on first render.\n        format_func : function\n            Function to modify the display of radio options. It receives\n            the raw option as an argument and should output the label to be\n            shown for that option. This has no impact on the return value of\n            the radio.\n        key : str or int\n            An optional string or integer to use as the unique key for the widget.\n            If this is omitted, a key will be generated for the widget\n            based on its content. Multiple widgets of the same type may\n            not share the same key.\n        help : str\n            An optional tooltip that gets displayed next to the radio.\n        on_change : callable\n            An optional callback invoked when this radio's value changes.\n        args : tuple\n            An optional tuple of args to pass to the callback.\n        kwargs : dict\n            An optional dict of kwargs to pass to the callback.\n        disabled : bool\n            An optional boolean, which disables the radio button if set to\n            True. The default is False. This argument can only be supplied by\n            keyword.\n        horizontal : bool\n            An optional boolean, which orients the radio group horizontally.\n            The default is false (vertical buttons). This argument can only\n            be supplied by keyword.\n\n        Returns\n        -------\n        any\n            The selected option.\n\n        Example\n        -------\n        >>> genre = st.radio(\n        ...     \"What\\'s your favorite movie genre\",\n        ...     ('Comedy', 'Drama', 'Documentary'))\n        >>>\n        >>> if genre == 'Comedy':\n        ...     st.write('You selected comedy.')\n        ... else:\n        ...     st.write(\"You didn\\'t select comedy.\")\n\n        .. output::\n           https://doc-radio.streamlitapp.com/\n           height: 260px\n\n        \"\"\"\n        ctx = get_script_run_ctx()\n        return self._radio(\n            label=label,\n            options=options,\n            index=index,\n            format_func=format_func,\n            key=key,\n            help=help,\n            on_change=on_change,\n            args=args,\n            kwargs=kwargs,\n            disabled=disabled,\n            horizontal=horizontal,\n            ctx=ctx,\n        )\n\n    def _radio(\n        self,\n        label: str,\n        options: OptionSequence,\n        index: int = 0,\n        format_func: Callable[[Any], Any] = str,\n        key: Optional[Key] = None,\n        help: Optional[str] = None,\n        on_change: Optional[WidgetCallback] = None,\n        args: Optional[WidgetArgs] = None,\n        kwargs: Optional[WidgetKwargs] = None,\n        *,  # keyword-only args:\n        disabled: bool = False,\n        horizontal: bool = False,\n        ctx: Optional[ScriptRunContext],\n    ) -> Any:\n        key = to_key(key)\n        check_callback_rules(self.dg, on_change)\n        check_session_state_rules(default_value=None if index == 0 else index, key=key)\n\n        opt = ensure_indexable(options)\n\n        if not isinstance(index, int):\n            raise StreamlitAPIException(\n                \"Radio Value has invalid type: %s\" % type(index).__name__\n            )\n\n        if len(opt) > 0 and not 0 <= index < len(opt):\n            raise StreamlitAPIException(\n                \"Radio index must be between 0 and length of options\"\n            )\n\n        radio_proto = RadioProto()\n        radio_proto.label = label\n        radio_proto.default = index\n        radio_proto.options[:] = [str(format_func(option)) for option in opt]\n        radio_proto.form_id = current_form_id(self.dg)\n        radio_proto.horizontal = horizontal\n        if help is not None:\n            radio_proto.help = dedent(help)\n\n        def deserialize_radio(ui_value, widget_id=\"\"):\n            idx = ui_value if ui_value is not None else index\n\n            return opt[idx] if len(opt) > 0 and opt[idx] is not None else None\n\n        def serialize_radio(v):\n            if len(options) == 0:\n                return 0\n            return index_(options, v)\n\n        widget_state = register_widget(\n            \"radio\",\n            radio_proto,\n            user_key=key,\n            on_change_handler=on_change,\n            args=args,\n            kwargs=kwargs,\n            deserializer=deserialize_radio,\n            serializer=serialize_radio,\n            ctx=ctx,\n        )\n\n        # This needs to be done after register_widget because we don't want\n        # the following proto fields to affect a widget's ID.\n        radio_proto.disabled = disabled\n        if widget_state.value_changed:\n            radio_proto.value = serialize_radio(widget_state.value)\n            radio_proto.set_value = True\n\n        self.dg._enqueue(\"radio\", radio_proto)\n        return widget_state.value\n\n    @property\n    def dg(self) -> \"streamlit.delta_generator.DeltaGenerator\":\n        \"\"\"Get our DeltaGenerator.\"\"\"\n        return cast(\"streamlit.delta_generator.DeltaGenerator\", self)\n", "path": "lib/streamlit/elements/radio.py"}], "after_files": [{"content": "# Copyright 2018-2022 Streamlit Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#    http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport pandas as pd\nimport streamlit as st\n\noptions = (\"female\", \"male\")\ni1 = st.radio(\"radio 1\", options, 1)\nst.write(\"value 1:\", i1)\n\ni2 = st.radio(\"radio 2\", options, 0, format_func=lambda x: x.capitalize())\nst.write(\"value 2:\", i2)\n\ni3 = st.radio(\"radio 3\", [])\nst.write(\"value 3:\", i3)\n\ni4 = st.radio(\"radio 4\", options, disabled=True)\nst.write(\"value 4:\", i4)\n\ni5 = st.radio(\"radio 5\", options, horizontal=True)\nst.write(\"value 5:\", i5)\n\ni6 = st.radio(\"radio 6\", pd.DataFrame({\"foo\": list(options)}))\nst.write(\"value 6:\", i6)\n\n\nif st._is_running_with_streamlit:\n\n    def on_change():\n        st.session_state.radio_changed = True\n\n    st.radio(\"radio 7\", options, 1, key=\"radio7\", on_change=on_change)\n    st.write(\"value 7:\", st.session_state.radio7)\n    st.write(\"radio changed:\", \"radio_changed\" in st.session_state)\n", "path": "e2e/scripts/st_radio.py"}, {"content": "# Copyright 2018-2022 Streamlit Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#    http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom textwrap import dedent\nfrom typing import Any, Callable, Optional, cast\n\nimport streamlit\nfrom streamlit.errors import StreamlitAPIException\nfrom streamlit.proto.Radio_pb2 import Radio as RadioProto\nfrom streamlit.scriptrunner import ScriptRunContext, get_script_run_ctx\nfrom streamlit.state import (\n    register_widget,\n    WidgetArgs,\n    WidgetCallback,\n    WidgetKwargs,\n)\nfrom streamlit.type_util import Key, OptionSequence, ensure_indexable, to_key\nfrom streamlit.util import index_\nfrom .form import current_form_id\nfrom .utils import check_callback_rules, check_session_state_rules\n\n\nclass RadioMixin:\n    def radio(\n        self,\n        label: str,\n        options: OptionSequence,\n        index: int = 0,\n        format_func: Callable[[Any], Any] = str,\n        key: Optional[Key] = None,\n        help: Optional[str] = None,\n        on_change: Optional[WidgetCallback] = None,\n        args: Optional[WidgetArgs] = None,\n        kwargs: Optional[WidgetKwargs] = None,\n        *,  # keyword-only args:\n        disabled: bool = False,\n        horizontal: bool = False,\n    ) -> Any:\n        \"\"\"Display a radio button widget.\n\n        Parameters\n        ----------\n        label : str\n            A short label explaining to the user what this radio group is for.\n        options : Sequence, numpy.ndarray, pandas.Series, pandas.DataFrame, or pandas.Index\n            Labels for the radio options. This will be cast to str internally\n            by default. For pandas.DataFrame, the first column is selected.\n        index : int\n            The index of the preselected option on first render.\n        format_func : function\n            Function to modify the display of radio options. It receives\n            the raw option as an argument and should output the label to be\n            shown for that option. This has no impact on the return value of\n            the radio.\n        key : str or int\n            An optional string or integer to use as the unique key for the widget.\n            If this is omitted, a key will be generated for the widget\n            based on its content. Multiple widgets of the same type may\n            not share the same key.\n        help : str\n            An optional tooltip that gets displayed next to the radio.\n        on_change : callable\n            An optional callback invoked when this radio's value changes.\n        args : tuple\n            An optional tuple of args to pass to the callback.\n        kwargs : dict\n            An optional dict of kwargs to pass to the callback.\n        disabled : bool\n            An optional boolean, which disables the radio button if set to\n            True. The default is False. This argument can only be supplied by\n            keyword.\n        horizontal : bool\n            An optional boolean, which orients the radio group horizontally.\n            The default is false (vertical buttons). This argument can only\n            be supplied by keyword.\n\n        Returns\n        -------\n        any\n            The selected option.\n\n        Example\n        -------\n        >>> genre = st.radio(\n        ...     \"What\\'s your favorite movie genre\",\n        ...     ('Comedy', 'Drama', 'Documentary'))\n        >>>\n        >>> if genre == 'Comedy':\n        ...     st.write('You selected comedy.')\n        ... else:\n        ...     st.write(\"You didn\\'t select comedy.\")\n\n        .. output::\n           https://doc-radio.streamlitapp.com/\n           height: 260px\n\n        \"\"\"\n        ctx = get_script_run_ctx()\n        return self._radio(\n            label=label,\n            options=options,\n            index=index,\n            format_func=format_func,\n            key=key,\n            help=help,\n            on_change=on_change,\n            args=args,\n            kwargs=kwargs,\n            disabled=disabled,\n            horizontal=horizontal,\n            ctx=ctx,\n        )\n\n    def _radio(\n        self,\n        label: str,\n        options: OptionSequence,\n        index: int = 0,\n        format_func: Callable[[Any], Any] = str,\n        key: Optional[Key] = None,\n        help: Optional[str] = None,\n        on_change: Optional[WidgetCallback] = None,\n        args: Optional[WidgetArgs] = None,\n        kwargs: Optional[WidgetKwargs] = None,\n        *,  # keyword-only args:\n        disabled: bool = False,\n        horizontal: bool = False,\n        ctx: Optional[ScriptRunContext],\n    ) -> Any:\n        key = to_key(key)\n        check_callback_rules(self.dg, on_change)\n        check_session_state_rules(default_value=None if index == 0 else index, key=key)\n\n        opt = ensure_indexable(options)\n\n        if not isinstance(index, int):\n            raise StreamlitAPIException(\n                \"Radio Value has invalid type: %s\" % type(index).__name__\n            )\n\n        if len(opt) > 0 and not 0 <= index < len(opt):\n            raise StreamlitAPIException(\n                \"Radio index must be between 0 and length of options\"\n            )\n\n        radio_proto = RadioProto()\n        radio_proto.label = label\n        radio_proto.default = index\n        radio_proto.options[:] = [str(format_func(option)) for option in opt]\n        radio_proto.form_id = current_form_id(self.dg)\n        radio_proto.horizontal = horizontal\n        if help is not None:\n            radio_proto.help = dedent(help)\n\n        def deserialize_radio(ui_value, widget_id=\"\"):\n            idx = ui_value if ui_value is not None else index\n\n            return opt[idx] if len(opt) > 0 and opt[idx] is not None else None\n\n        def serialize_radio(v):\n            if len(opt) == 0:\n                return 0\n            return index_(opt, v)\n\n        widget_state = register_widget(\n            \"radio\",\n            radio_proto,\n            user_key=key,\n            on_change_handler=on_change,\n            args=args,\n            kwargs=kwargs,\n            deserializer=deserialize_radio,\n            serializer=serialize_radio,\n            ctx=ctx,\n        )\n\n        # This needs to be done after register_widget because we don't want\n        # the following proto fields to affect a widget's ID.\n        radio_proto.disabled = disabled\n        if widget_state.value_changed:\n            radio_proto.value = serialize_radio(widget_state.value)\n            radio_proto.set_value = True\n\n        self.dg._enqueue(\"radio\", radio_proto)\n        return widget_state.value\n\n    @property\n    def dg(self) -> \"streamlit.delta_generator.DeltaGenerator\":\n        \"\"\"Get our DeltaGenerator.\"\"\"\n        return cast(\"streamlit.delta_generator.DeltaGenerator\", self)\n", "path": "lib/streamlit/elements/radio.py"}]}