Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf: use class_traits with a cache to speed up creation of widgets #3020

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion ipywidgets/widgets/tests/test_traits.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from traitlets import HasTraits, Int, TraitError
from traitlets.tests.test_traitlets import TraitTestBase

from ipywidgets import Color, NumberFormat
from ipywidgets import Button, Color, NumberFormat
from ipywidgets.widgets.widget import _remove_buffers, _put_buffers
from ipywidgets.widgets.trait_types import date_serialization, TypedTuple

Expand Down Expand Up @@ -243,3 +243,13 @@ class TestCase(HasTraits):

obj = TestCase()
assert obj.value == (1, 2, 3)


def test_add_trait():
button = Button()
keys = list(button.keys)
assert 'foobar' not in keys
button.add_traits(foobar=Int().tag(sync=True))
assert 'foobar' in button.keys
assert 'foobar' not in Button().keys
assert set(button.keys) != set(keys)
14 changes: 11 additions & 3 deletions ipywidgets/widgets/widget.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from collections.abc import Iterable
from IPython import get_ipython
from ipykernel.comm import Comm
import functools
from traitlets import (
HasTraits, Unicode, Dict, Instance, List, Int, Set, Bytes, observe, default, Container,
Undefined)
Expand Down Expand Up @@ -367,7 +368,7 @@ def get_view_spec(self):

@default('keys')
def _default_keys(self):
return [name for name in self.traits(sync=True)]
return [name for name in self.class_traits(sync=True)]

_property_lock = Dict()
_holding_sync = False
Expand Down Expand Up @@ -483,7 +484,7 @@ def get_state(self, key=None, drop_defaults=False):
else:
raise ValueError("key must be a string, an iterable of keys, or None")
state = {}
traits = self.traits()
traits = self.class_traits()
for k in keys:
to_json = self.trait_metadata(k, 'to_json', self._trait_to_json)
value = to_json(getattr(self, k), self)
Expand Down Expand Up @@ -547,6 +548,13 @@ def add_traits(self, **traits):
self.keys.append(name)
self.send_state(name)

@classmethod
@functools.lru_cache(None)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I feel like an unlimited cache size is a bit dangerous. Maybe it's not in practice though?

def class_traits(cls, **metadata):
# we cache it for performance reasons
return super().class_traits(**metadata)


def notify_change(self, change):
"""Called when a property has changed."""
# Send the state to the frontend before the user-registered callbacks
Expand Down Expand Up @@ -682,7 +690,7 @@ def _send(self, msg, buffers=None):
self.comm.send(data=msg, buffers=buffers)

def _repr_keys(self):
traits = self.traits()
traits = self.class_traits()
for key in sorted(self.keys):
# Exclude traits that start with an underscore
if key[0] == '_':
Expand Down