Skip to content

Commit

Permalink
added try except block in state.py (#5790)
Browse files Browse the repository at this point in the history
* added try except block in `state.py`

added try except block in `state.py` which will raise a "ValueError"

* add changeset

* updated `state.py` and added test for deepcopy

updated `state.py` and added test for deepcopy named test_initial_value_deepcopy in `test/test_components.py`

* lint

* test fix

* explain test

---------

Co-authored-by: Abubakar Abid <abubakar@huggingface.co>
Co-authored-by: gradio-pr-bot <gradio-pr-bot@users.noreply.github.com>
  • Loading branch information
3 people committed Oct 5, 2023
1 parent 4567788 commit 37e7084
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/hot-ducks-end.md
@@ -0,0 +1,5 @@
---
"gradio": patch
---

fix:added try except block in `state.py`
8 changes: 7 additions & 1 deletion gradio/components/state.py
Expand Up @@ -37,7 +37,13 @@ def __init__(
value: the initial value (of arbitrary type) of the state. The provided argument is deepcopied. If a callable is provided, the function will be called whenever the app loads to set the initial value of the state.
"""
self.stateful = True
IOComponent.__init__(self, value=deepcopy(value), **kwargs)
try:
self.value = deepcopy(value)
except TypeError as err:
raise TypeError(
f"The initial value of `gr.State` must be able to be deepcopied. The initial value of type {type(value)} cannot be deepcopied."
) from err
IOComponent.__init__(self, value=self.value, **kwargs)


class Variable(State):
Expand Down
4 changes: 4 additions & 0 deletions test/test_components.py
Expand Up @@ -2417,6 +2417,10 @@ def test_as_component(self):
assert state.preprocess("abc") == "abc"
assert state.stateful

def test_initial_value_deepcopy(self):
with pytest.raises(TypeError):
gr.State(value=gr) # modules are not deepcopyable

@pytest.mark.asyncio
async def test_in_interface(self):
def test(x, y=" def"):
Expand Down

0 comments on commit 37e7084

Please sign in to comment.