Skip to content

Commit

Permalink
V4: Fix constructor_args (#6093)
Browse files Browse the repository at this point in the history
* Fix

* add changeset

---------

Co-authored-by: gradio-pr-bot <gradio-pr-bot@users.noreply.github.com>
  • Loading branch information
freddyaboulton and gradio-pr-bot committed Oct 26, 2023
1 parent 11d67ae commit fadc057
Show file tree
Hide file tree
Showing 5 changed files with 28 additions and 3 deletions.
5 changes: 5 additions & 0 deletions .changeset/funny-dodos-sip.md
@@ -0,0 +1,5 @@
---
"gradio": minor
---

feat:V4: Fix constructor_args
12 changes: 11 additions & 1 deletion gradio/blocks.py
Expand Up @@ -113,7 +113,7 @@ def __init__(
self._skip_init_processing = _skip_init_processing
self.parent: BlockContext | None = None
self.is_rendered: bool = False
self.constructor_args: dict
self._constructor_args: dict
self.state_session_capacity = 10000

if render:
Expand All @@ -123,6 +123,16 @@ def __init__(
def skip_api(self):
return False

@property
def constructor_args(self) -> dict[str, Any]:
"""Get the arguments passed to the component's initializer.
Only set classes whose metaclass is ComponentMeta
"""
# the _constructor_args list is appended based on the mro of the class
# so the first entry is for the bottom of the hierarchy
return self._constructor_args[0] if self._constructor_args else {}

@property
def events(
self,
Expand Down
4 changes: 3 additions & 1 deletion gradio/component_meta.py
Expand Up @@ -139,12 +139,14 @@ def updateable(fn):
def wrapper(*args, **kwargs):
fn_args = inspect.getfullargspec(fn).args
self = args[0]
if not hasattr(self, "_constructor_args"):
self._constructor_args = []
for i, arg in enumerate(args):
if i == 0 or i >= len(fn_args): # skip self, *args
continue
arg_name = fn_args[i]
kwargs[arg_name] = arg
self.constructor_args = kwargs
self._constructor_args.append(kwargs)
if in_event_listener():
return None
else:
Expand Down
2 changes: 1 addition & 1 deletion gradio/events.py
Expand Up @@ -287,7 +287,7 @@ def inner(*args, **kwargs):

if Context.root_block is None:
raise AttributeError(
"Cannot call {self.event_name} outside of a gradio.Blocks context."
f"Cannot call {_event_name} outside of a gradio.Blocks context."
)

dep, dep_index = Context.root_block.set_event_trigger(
Expand Down
8 changes: 8 additions & 0 deletions test/test_components.py
Expand Up @@ -2649,3 +2649,11 @@ def test_component_class_ids():

# Make sure that the ids are unique
assert len({button_id, textbox_id, json_id, microphone_id, audio_id}) == 5


def test_constructor_args():
assert gr.Textbox(max_lines=314).constructor_args == {"max_lines": 314}
assert gr.LoginButton(icon="F00.svg", value="Log in please").constructor_args == {
"icon": "F00.svg",
"value": "Log in please",
}

0 comments on commit fadc057

Please sign in to comment.