holoviews.ipython Package#


ipython Package#

class holoviews.ipython.IPTestCase(*args, **kwargs)[source]#

Bases: ComparisonTestCase

This class extends ComparisonTestCase to handle IPython specific objects and support the execution of cells and magic.

classmethod addClassCleanup(function, /, *args, **kwargs)[source]#

Same as addCleanup, except the cleanup items are called even if setUpClass fails (unlike tearDownClass).

addCleanup(function, /, *args, **kwargs)[source]#

Add a function, with arguments, to be called when the test is completed. Functions added are called on a LIFO basis and are called after tearDown on test failure or success.

Cleanup items are called even if setUp fails (unlike tearDown).

addTypeEqualityFunc(typeobj, function)[source]#

Add a type specific assertEqual style function to compare a type.

This method is for use by TestCase subclasses that need to register their own type equality functions to provide nicer error messages.

Args:
typeobj: The data type to call this function on when both values

are of the same type in assertEqual().

function: The callable taking two arguments and an optional

msg= argument that raises self.failureException with a useful error message when the two arguments are not equal.

assertAlmostEqual(first, second, places=None, msg=None, delta=None)[source]#

Fail if the two objects are unequal as determined by their difference rounded to the given number of decimal places (default 7) and comparing to zero, or by comparing that the difference between the two objects is more than the given delta.

Note that decimal places (from zero) are usually not the same as significant digits (measured from the most significant digit).

If the two objects compare equal then they will automatically compare almost equal.

assertCountEqual(first, second, msg=None)[source]#

Asserts that two iterables have the same elements, the same number of times, without regard to order.

self.assertEqual(Counter(list(first)),

Counter(list(second)))

Example:
  • [0, 1, 1] and [1, 0, 1] compare equal.

  • [0, 0, 1] and [0, 1] compare unequal.

assertDictContainsSubset(subset, dictionary, msg=None)[source]#

Checks whether dictionary is a superset of subset.

classmethod assertEqual(first, second, msg=None)[source]#

Classmethod equivalent to unittest.TestCase method

assertFalse(expr, msg=None)[source]#

Check that the expression is false.

assertGreater(a, b, msg=None)[source]#

Just like self.assertTrue(a > b), but with a nicer default message.

assertGreaterEqual(a, b, msg=None)[source]#

Just like self.assertTrue(a >= b), but with a nicer default message.

assertIn(member, container, msg=None)[source]#

Just like self.assertTrue(a in b), but with a nicer default message.

assertIs(expr1, expr2, msg=None)[source]#

Just like self.assertTrue(a is b), but with a nicer default message.

assertIsInstance(obj, cls, msg=None)[source]#

Same as self.assertTrue(isinstance(obj, cls)), with a nicer default message.

assertIsNone(obj, msg=None)[source]#

Same as self.assertTrue(obj is None), with a nicer default message.

assertIsNot(expr1, expr2, msg=None)[source]#

Just like self.assertTrue(a is not b), but with a nicer default message.

assertIsNotNone(obj, msg=None)[source]#

Included for symmetry with assertIsNone.

assertLess(a, b, msg=None)[source]#

Just like self.assertTrue(a < b), but with a nicer default message.

assertLessEqual(a, b, msg=None)[source]#

Just like self.assertTrue(a <= b), but with a nicer default message.

assertListEqual(list1, list2, msg=None)[source]#

A list-specific equality assertion.

Args:

list1: The first list to compare. list2: The second list to compare. msg: Optional message to use on failure instead of a list of

differences.

assertLogs(logger=None, level=None)[source]#

Fail unless a log message of level level or higher is emitted on logger_name or its children. If omitted, level defaults to INFO and logger defaults to the root logger.

This method must be used as a context manager, and will yield a recording object with two attributes: output and records. At the end of the context manager, the output attribute will be a list of the matching formatted log messages and the records attribute will be a list of the corresponding LogRecord objects.

Example:

with self.assertLogs('foo', level='INFO') as cm:
    logging.getLogger('foo').info('first message')
    logging.getLogger('foo.bar').error('second message')
self.assertEqual(cm.output, ['INFO:foo:first message',
                             'ERROR:foo.bar:second message'])
assertMultiLineEqual(first, second, msg=None)[source]#

Assert that two multi-line strings are equal.

assertNoLogs(logger=None, level=None)[source]#

Fail unless no log messages of level level or higher are emitted on logger_name or its children.

This method must be used as a context manager.

assertNotAlmostEqual(first, second, places=None, msg=None, delta=None)[source]#

Fail if the two objects are equal as determined by their difference rounded to the given number of decimal places (default 7) and comparing to zero, or by comparing that the difference between the two objects is less than the given delta.

Note that decimal places (from zero) are usually not the same as significant digits (measured from the most significant digit).

Objects that are equal automatically fail.

assertNotEqual(first, second, msg=None)[source]#

Fail if the two objects are equal as determined by the ‘!=’ operator.

assertNotIn(member, container, msg=None)[source]#

Just like self.assertTrue(a not in b), but with a nicer default message.

assertNotIsInstance(obj, cls, msg=None)[source]#

Included for symmetry with assertIsInstance.

assertNotRegex(text, unexpected_regex, msg=None)[source]#

Fail the test if the text matches the regular expression.

assertRaises(expected_exception, *args, **kwargs)[source]#

Fail unless an exception of class expected_exception is raised by the callable when invoked with specified positional and keyword arguments. If a different type of exception is raised, it will not be caught, and the test case will be deemed to have suffered an error, exactly as for an unexpected exception.

If called with the callable and arguments omitted, will return a context object used like this:

with self.assertRaises(SomeException):
    do_something()

An optional keyword argument ‘msg’ can be provided when assertRaises is used as a context object.

The context manager keeps a reference to the exception as the ‘exception’ attribute. This allows you to inspect the exception after the assertion:

with self.assertRaises(SomeException) as cm:
    do_something()
the_exception = cm.exception
self.assertEqual(the_exception.error_code, 3)
assertRaisesRegex(expected_exception, expected_regex, *args, **kwargs)[source]#

Asserts that the message in a raised exception matches a regex.

Args:

expected_exception: Exception class expected to be raised. expected_regex: Regex (re.Pattern object or string) expected

to be found in error message.

args: Function to be called and extra positional args. kwargs: Extra kwargs. msg: Optional message used in case of failure. Can only be used

when assertRaisesRegex is used as a context manager.

assertRegex(text, expected_regex, msg=None)[source]#

Fail the test unless the text matches the regular expression.

assertSequenceEqual(seq1, seq2, msg=None, seq_type=None)[source]#

An equality assertion for ordered sequences (like lists and tuples).

For the purposes of this function, a valid ordered sequence type is one which can be indexed, has a length, and has an equality operator.

Args:

seq1: The first sequence to compare. seq2: The second sequence to compare. seq_type: The expected datatype of the sequences, or None if no

datatype should be enforced.

msg: Optional message to use on failure instead of a list of

differences.

assertSetEqual(set1, set2, msg=None)[source]#

A set-specific equality assertion.

Args:

set1: The first set to compare. set2: The second set to compare. msg: Optional message to use on failure instead of a list of

differences.

assertSetEqual uses ducktyping to support different types of sets, and is optimized for sets specifically (parameters must support a difference method).

assertTrue(expr, msg=None)[source]#

Check that the expression is true.

assertTupleEqual(tuple1, tuple2, msg=None)[source]#

A tuple-specific equality assertion.

Args:

tuple1: The first tuple to compare. tuple2: The second tuple to compare. msg: Optional message to use on failure instead of a list of

differences.

assertWarns(expected_warning, *args, **kwargs)[source]#

Fail unless a warning of class warnClass is triggered by the callable when invoked with specified positional and keyword arguments. If a different type of warning is triggered, it will not be handled: depending on the other warning filtering rules in effect, it might be silenced, printed out, or raised as an exception.

If called with the callable and arguments omitted, will return a context object used like this:

with self.assertWarns(SomeWarning):
    do_something()

An optional keyword argument ‘msg’ can be provided when assertWarns is used as a context object.

The context manager keeps a reference to the first matching warning as the ‘warning’ attribute; similarly, the ‘filename’ and ‘lineno’ attributes give you information about the line of Python code from which the warning was triggered. This allows you to inspect the warning after the assertion:

with self.assertWarns(SomeWarning) as cm:
    do_something()
the_warning = cm.warning
self.assertEqual(the_warning.some_attribute, 147)
assertWarnsRegex(expected_warning, expected_regex, *args, **kwargs)[source]#

Asserts that the message in a triggered warning matches a regexp. Basic functioning is similar to assertWarns() with the addition that only warnings whose messages also match the regular expression are considered successful matches.

Args:

expected_warning: Warning class expected to be triggered. expected_regex: Regex (re.Pattern object or string) expected

to be found in error message.

args: Function to be called and extra positional args. kwargs: Extra kwargs. msg: Optional message used in case of failure. Can only be used

when assertWarnsRegex is used as a context manager.

assert_array_almost_equal_fn(desired, *, decimal=6, err_msg='', verbose=True)#

Raises an AssertionError if two objects are not equal up to desired precision.

Note

It is recommended to use one of assert_allclose, assert_array_almost_equal_nulp or assert_array_max_ulp instead of this function for more consistent floating point comparisons.

The test verifies identical shapes and that the elements of actual and desired satisfy:

abs(desired-actual) < 1.5 * 10**(-decimal)

That is a looser test than originally documented, but agrees with what the actual implementation did up to rounding vagaries. An exception is raised at shape mismatch or conflicting values. In contrast to the standard usage in numpy, NaNs are compared like numbers, no assertion is raised if both objects have NaNs in the same positions.

Parameters#

actualarray_like

The actual object to check.

desiredarray_like

The desired, expected object.

decimalint, optional

Desired precision, default is 6.

err_msgstr, optional

The error message to be printed in case of failure.

verbosebool, optional

If True, the conflicting values are appended to the error message.

Raises#

AssertionError

If actual and desired are not equal up to specified precision.

See Also#

assert_allclose: Compare two array_like objects for equality with desired

relative and/or absolute precision.

assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal

Examples#

the first assert does not raise an exception

>>> np.testing.assert_array_almost_equal([1.0,2.333,np.nan],
...                                      [1.0,2.333,np.nan])
>>> np.testing.assert_array_almost_equal([1.0,2.33333,np.nan],
...                                      [1.0,2.33339,np.nan], decimal=5)
Traceback (most recent call last):
    ...
AssertionError:
Arrays are not almost equal to 5 decimals

Mismatched elements: 1 / 3 (33.3%)
Max absolute difference among violations: 6.e-05
Max relative difference among violations: 2.57136612e-05
 ACTUAL: array([1.     , 2.33333,     nan])
 DESIRED: array([1.     , 2.33339,     nan])
>>> np.testing.assert_array_almost_equal([1.0,2.33333,np.nan],
...                                      [1.0,2.33333, 5], decimal=5)
Traceback (most recent call last):
    ...
AssertionError:
Arrays are not almost equal to 5 decimals

nan location mismatch:
 ACTUAL: array([1.     , 2.33333,     nan])
 DESIRED: array([1.     , 2.33333, 5.     ])
cell(line)[source]#

Run an IPython cell

cell_magic(*args, **kwargs)[source]#

Run an IPython cell magic

debug()[source]#

Run the test without collecting errors in a TestResult

classmethod doClassCleanups()[source]#

Execute all class cleanup functions. Normally called for you after tearDownClass.

doCleanups()[source]#

Execute all cleanup functions. Normally called for you after tearDown.

classmethod enterClassContext(cm)[source]#

Same as enterContext, but class-wide.

enterContext(cm)[source]#

Enters the supplied context manager.

If successful, also adds its __exit__ method as a cleanup function and returns the result of the __enter__ method.

fail(msg=None)[source]#

Fail immediately, with the given message.

failureException#

alias of AssertionError

line_magic(*args, **kwargs)[source]#

Run an IPython line magic

setUp()[source]#

Hook method for setting up the test fixture before exercising it.

classmethod setUpClass()[source]#

Hook method for setting up class fixture before running tests in the class.

shortDescription()[source]#

Returns a one-line description of the test, or None if no description has been provided.

The default implementation of this method returns the first line of the specified test method’s docstring.

classmethod simple_equality(first, second, msg=None)[source]#

Classmethod equivalent to unittest.TestCase method (longMessage = False.)

skipTest(reason)[source]#

Skip this test.

subTest(msg=<object object>, **params)[source]#

Return a context manager that will return the enclosed block of code in a subtest identified by the optional message and keyword parameters. A failure in the subtest marks the test case as failed but resumes execution at the end of the enclosed block, allowing further test code to be executed.

tearDown()[source]#

Hook method for deconstructing the test fixture after testing it.

classmethod tearDownClass()[source]#

Hook method for deconstructing the class fixture after running all tests in the class.

class holoviews.ipython.notebook_extension(*, allow_jedi_completion, case_sensitive_completion, css, display_formats, enable_mathjax, inline, logo, width, name)[source]#

Bases: extension

Notebook specific extension to hv.extension that offers options for controlling the notebook environment.

css = param.String(allow_refs=False, default=’’, label=’Css’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x15c822090>)

Optional CSS rule set to apply to the notebook.

logo = param.Boolean(allow_refs=False, default=True, label=’Logo’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x15c5a18d0>)

Toggles display of HoloViews logo

inline = param.Boolean(allow_refs=False, default=False, label=’Inline’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x15c62a190>)

Whether to inline JS and CSS resources. If disabled, resources are loaded from CDN if one is available.

width = param.Number(allow_None=True, allow_refs=False, bounds=(0, 100), inclusive_bounds=(True, True), label=’Width’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x15c647b10>)

Width of the notebook as a percentage of the browser screen window width.

display_formats = param.List(allow_refs=False, bounds=(0, None), default=[‘html’], label=’Display formats’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x15c6a6ed0>)

A list of formats that are rendered to the notebook where multiple formats may be selected at once (although only one format will be displayed). Although the ‘html’ format is supported across backends, other formats supported by the current backend (e.g. ‘png’ and ‘svg’ using the matplotlib backend) may be used. This may be useful to export figures to other formats such as PDF with nbconvert.

allow_jedi_completion = param.Boolean(allow_refs=False, default=True, label=’Allow jedi completion’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x15c830390>)

Whether to allow jedi tab-completion to be enabled in IPython. Disabled by default because many HoloViews features rely on tab-completion machinery not supported when using jedi.

case_sensitive_completion = param.Boolean(allow_refs=False, default=False, label=’Case sensitive completion’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x15c5d4990>)

Whether to monkey patch IPython to use the correct tab-completion behavior.

enable_mathjax = param.Boolean(allow_refs=False, default=False, label=’Enable mathjax’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x156f19d50>)

Whether to load bokeh-mathjax bundle in the notebook.

classmethod completions_sorting_key(word)[source]#

Fixed version of IPyton.completer.completions_sorting_key

classmethod instance(**params)[source]#

Return an instance of this class, copying parameters from any existing instance provided.

Allow to display Holoviews’ logo and the plotting extensions’ logo.

classmethod register_backend_callback(backend, callback)[source]#

Registers a hook which is run when a backend is loaded

holoviews.ipython.show_traceback()[source]#

Display the full traceback after an abbreviated traceback has occurred.


archive Module#

Implements NotebookArchive used to automatically capture notebook data and export it to disk via the display hooks.

class holoviews.ipython.archive.NotebookArchive(*, skip_notebook_export, snapshot_name, archive_format, dimension_formatter, export_name, filename_formatter, flush_archive, max_filename, object_formatter, pack, root, timestamp_format, unique_name, exporters, name)[source]#

Bases: FileArchive

FileArchive that can automatically capture notebook data via the display hooks and automatically adds a notebook HTML snapshot to the archive upon export.

Parameters inherited from:

holoviews.core.io.FileArchive: dimension_formatter, object_formatter, timestamp_format, root, archive_format, pack, unique_name, max_filename, flush_archive

exporters = param.List(allow_refs=False, bounds=(0, None), default=[<class ‘holoviews.core.io.Pickler’>], label=’Exporters’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x15d612350>)

The exporter functions used to convert HoloViews objects into the appropriate format(s).

filename_formatter = param.String(allow_refs=False, default=’{dimensions},{obj}’, label=’Filename formatter’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x15d5ccad0>)

Similar to FileArchive.filename_formatter except with support for the notebook name field as {notebook}.

export_name = param.String(allow_refs=False, default=’{notebook}’, label=’Export name’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x15d6122d0>)

Similar to FileArchive.filename_formatter except with support for the notebook name field as {notebook}.

skip_notebook_export = param.Boolean(allow_refs=False, default=False, label=’Skip notebook export’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x15d4f0610>)

Whether to skip JavaScript capture of notebook data which may be unreliable. Also disabled automatic capture of notebook name.

snapshot_name = param.String(allow_refs=False, default=’index’, label=’Snapshot name’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x15d612510>)

The basename of the exported notebook snapshot (html). It may optionally use the {timestamp} formatter.

add(obj=None, filename=None, data=None, info=None, html=None)[source]#

Similar to FileArchive.add but accepts html strings for substitution

auto(enabled=Boolean, name=String, exporters=List, dimension_formatter=String, object_formatter=Callable, filename_formatter=String, timestamp_format=String, root=String, archive_format=ObjectSelector, pack=Boolean, export_name=String, unique_name=Boolean, max_filename=Integer, flush_archive=Boolean, skip_notebook_export=Boolean, snapshot_name=String)[source]#
clear()[source]#

Clears the file archive

contents(maxlen=70)[source]#

Print the current (unexported) contents of the archive

export(timestamp=None)[source]#

Get the current notebook data and export.

get_namespace()[source]#

Find the name the user is using to access holoviews.

last_export_status()[source]#

Helper to show the status of the last call to the export method.

listing()[source]#

Return a list of filename entries currently in the archive

object_formatter()[source]#

Simple name_generator designed for HoloViews objects.

Objects are labeled with {group}-{label} for each nested object, based on a depth-first search. Adjacent objects with identical representations yield only a single copy of the representation, to avoid long names for the common case of a container whose element(s) share the same group and label.

classmethod parse_fields(formatter)[source]#

Returns the format fields otherwise raise exception


display_hooks Module#

Definition and registration of display hooks for the IPython Notebook.

holoviews.ipython.display_hooks.display(obj, raw_output=False, **kwargs)[source]#

Renders any HoloViews object to HTML and displays it using the IPython display function. If raw is enabled the raw HTML is returned instead of displaying it directly.

holoviews.ipython.display_hooks.display_hook(fn)[source]#

A decorator to wrap display hooks that return a MIME bundle or None. Additionally it handles adding output to the notebook archive, saves files specified with the output magic and handles tracebacks.

holoviews.ipython.display_hooks.first_frame(obj)[source]#

Only display the first frame of an animated plot

holoviews.ipython.display_hooks.image_display(element, max_frames, fmt)[source]#

Used to render elements to an image format (svg or png) if requested in the display formats.

holoviews.ipython.display_hooks.last_frame(obj)[source]#

Only display the last frame of an animated plot

holoviews.ipython.display_hooks.middle_frame(obj)[source]#

Only display the (approximately) middle frame of an animated plot

holoviews.ipython.display_hooks.png_display(element, max_frames)[source]#

Used to render elements to PNG if requested in the display formats.

holoviews.ipython.display_hooks.process_object(obj)[source]#

Hook to process the object currently being displayed.

holoviews.ipython.display_hooks.single_frame_plot(obj)[source]#

Returns plot, renderer and format for single frame export.

holoviews.ipython.display_hooks.svg_display(element, max_frames)[source]#

Used to render elements to SVG if requested in the display formats.


magics Module#

class holoviews.ipython.magics.CompositorMagic(**kwargs: Any)[source]#

Bases: Magics

Magic allowing easy definition of compositor operations. Consult %compositor? for more information.

add_traits(**traits: Any) None[source]#

Dynamically add trait attributes to the HasTraits instance.

arg_err(func)[source]#

Print docstring if incorrect arguments were passed

classmethod class_config_rst_doc() str[source]#

Generate rST documentation for this class’ config options.

Excludes traits defined on parent classes.

classmethod class_config_section(classes: Sequence[type[HasTraits]] | None = None) str[source]#

Get the config section for this class.

Parameters#

classeslist, optional

The list of other classes in the config file. Used to reduce redundant information.

classmethod class_get_help(inst: HasTraits | None = None) str[source]#

Get the help string for this class in ReST format.

If inst is given, its current trait values will be used in place of class defaults.

classmethod class_get_trait_help(trait: TraitType[Any, Any], inst: HasTraits | None = None, helptext: str | None = None) str[source]#

Get the helptext string for a single trait.

Parameters:
  • inst – If given, its current trait values will be used in place of the class default.

  • helptext – If not given, uses the help attribute of the current trait.

classmethod class_own_trait_events(name: str) dict[str, EventHandler][source]#

Get a dict of all event handlers defined on this class, not a parent.

Works like event_handlers, except for excluding traits from parents.

classmethod class_own_traits(**metadata: Any) dict[str, TraitType[Any, Any]][source]#

Get a dict of all the traitlets defined on this class, not a parent.

Works like class_traits, except for excluding traits from parents.

classmethod class_print_help(inst: HasTraits | None = None) None[source]#

Get the help string for a single trait and print it.

classmethod class_trait_names(**metadata: Any) list[str][source]#

Get a list of all the names of this class’ traits.

This method is just like the trait_names() method, but is unbound.

classmethod class_traits(**metadata: Any) dict[str, TraitType[Any, Any]][source]#

Get a dict of all the traits of this class. The dictionary is keyed on the name and the values are the TraitType objects.

This method is just like the traits() method, but is unbound.

The TraitTypes returned don’t know anything about the values that the various HasTrait’s instances are holding.

The metadata kwargs allow functions to be passed in which filter traits based on metadata values. The functions should take a single value as an argument and return a boolean. If any function returns False, then the trait is not included in the output. If a metadata key doesn’t exist, None will be passed to the function.

property cross_validation_lock: Any#

A contextmanager for running a block with our cross validation lock set to True.

At the end of the block, the lock’s value is restored to its value prior to entering the block.

default_option(fn, optstr)[source]#

Make an entry in the options_table for fn, with value optstr

format_latex(strng)[source]#

Format a string for latex inclusion.

has_trait(name: str) bool[source]#

Returns True if the object has a trait with the specified name.

hold_trait_notifications() Any[source]#

Context manager for bundling trait change notifications and cross validation.

Use this when doing multiple trait assignments (init, config), to avoid race conditions in trait notifiers requesting other trait values. All trait notifications will fire after all values have been assigned.

notify_change(change: Bunch) None[source]#

Notify observers of a change event

observe(handler: Callable[[...], Any], names: Sentinel | str | Iterable[Sentinel | str] = traitlets.All, type: Sentinel | str = 'change') None[source]#

Setup a handler to be called when a trait changes.

This is used to setup dynamic notifications of trait changes.

Parameters#

handlercallable

A callable that is called when a trait changes. Its signature should be handler(change), where change is a dictionary. The change dictionary at least holds a ‘type’ key. * type: the type of notification. Other keys may be passed depending on the value of ‘type’. In the case where type is ‘change’, we also have the following keys: * owner : the HasTraits instance * old : the old value of the modified trait attribute * new : the new value of the modified trait attribute * name : the name of the modified trait attribute.

nameslist, str, All

If names is All, the handler will apply to all traits. If a list of str, handler will apply to all names in the list. If a str, the handler will apply just to that name.

typestr, All (default: ‘change’)

The type of notification to filter by. If equal to All, then all notifications are passed to the observe handler.

on_trait_change(handler: EventHandler | None = None, name: Sentinel | str | None = None, remove: bool = False) None[source]#

DEPRECATED: Setup a handler to be called when a trait changes.

This is used to setup dynamic notifications of trait changes.

Static handlers can be created by creating methods on a HasTraits subclass with the naming convention ‘_[traitname]_changed’. Thus, to create static handler for the trait ‘a’, create the method _a_changed(self, name, old, new) (fewer arguments can be used, see below).

If remove is True and handler is not specified, all change handlers for the specified name are uninstalled.

Parameters#

handlercallable, None

A callable that is called when a trait changes. Its signature can be handler(), handler(name), handler(name, new), handler(name, old, new), or handler(name, old, new, self).

namelist, str, None

If None, the handler will apply to all traits. If a list of str, handler will apply to all names in the list. If a str, the handler will apply just to that name.

removebool

If False (the default), then install the handler. If True then unintall it.

parse_options(arg_str, opt_str, *long_opts, **kw)[source]#

Parse options passed to an argument string.

The interface is similar to that of getopt.getopt(), but it returns a Struct with the options as keys and the stripped argument string still as a string.

arg_str is quoted as a true sys.argv vector by using shlex.split. This allows us to easily expand variables, glob files, quote arguments, etc.

Parameters#

arg_strstr

The arguments to parse.

opt_strstr

The options specification.

modestr, default ‘string’

If given as ‘list’, the argument string is returned as a list (split on whitespace) instead of a string.

list_allbool, default False

Put all option values in lists. Normally only options appearing more than once are put in a list.

posixbool, default True

Whether to split the input line in POSIX mode or not, as per the conventions outlined in the shlex module from the standard library.

classmethod section_names() list[str][source]#

return section names as a list

set_trait(name: str, value: Any) None[source]#

Forcibly sets trait attribute, including read-only attributes.

setup_instance(**kwargs: Any) None[source]#

This is called before self.__init__ is called.

trait_defaults(*names: str, **metadata: Any) dict[str, Any] | Sentinel[source]#

Return a trait’s default value or a dictionary of them

Notes#

Dynamically generated default values may depend on the current state of the object.

classmethod trait_events(name: str | None = None) dict[str, EventHandler][source]#

Get a dict of all the event handlers of this class.

Parameters#

namestr (default: None)

The name of a trait of this class. If name is None then all the event handlers of this class will be returned instead.

Returns#

The event handlers associated with a trait name, or all event handlers.

trait_has_value(name: str) bool[source]#

Returns True if the specified trait has a value.

This will return false even if getattr would return a dynamically generated default value. These default values will be recognized as existing only after they have been generated.

Example

class MyClass(HasTraits):
    i = Int()


mc = MyClass()
assert not mc.trait_has_value("i")
mc.i  # generates a default value
assert mc.trait_has_value("i")
trait_metadata(traitname: str, key: str, default: Any = None) Any[source]#

Get metadata values for trait by key.

trait_names(**metadata: Any) list[str][source]#

Get a list of all the names of this class’ traits.

trait_values(**metadata: Any) dict[str, Any][source]#

A dict of trait names and their values.

The metadata kwargs allow functions to be passed in which filter traits based on metadata values. The functions should take a single value as an argument and return a boolean. If any function returns False, then the trait is not included in the output. If a metadata key doesn’t exist, None will be passed to the function.

Returns#

A dict of trait names and their values.

Notes#

Trait values are retrieved via getattr, any exceptions raised by traits or the operations they may trigger will result in the absence of a trait value in the result dict.

traits(**metadata: Any) dict[str, TraitType[Any, Any]][source]#

Get a dict of all the traits of this class. The dictionary is keyed on the name and the values are the TraitType objects.

The TraitTypes returned don’t know anything about the values that the various HasTrait’s instances are holding.

The metadata kwargs allow functions to be passed in which filter traits based on metadata values. The functions should take a single value as an argument and return a boolean. If any function returns False, then the trait is not included in the output. If a metadata key doesn’t exist, None will be passed to the function.

unobserve(handler: Callable[[...], Any], names: Sentinel | str | Iterable[Sentinel | str] = traitlets.All, type: Sentinel | str = 'change') None[source]#

Remove a trait change handler.

This is used to unregister handlers to trait change notifications.

Parameters#

handlercallable

The callable called when a trait attribute changes.

nameslist, str, All (default: All)

The names of the traits for which the specified handler should be uninstalled. If names is All, the specified handler is uninstalled from the list of notifiers corresponding to all changes.

typestr or All (default: ‘change’)

The type of notification to filter by. If All, the specified handler is uninstalled from the list of notifiers corresponding to all types.

unobserve_all(name: str | Any = traitlets.All) None[source]#

Remove trait change handlers of any type for the specified name. If name is not specified, removes all trait notifiers.

update_config(config: Config) None[source]#

Update config and load the new values

class holoviews.ipython.magics.OptsCompleter[source]#

Bases: object

Implements the TAB-completion for the %%opts magic.

classmethod dotted_completion(line, sorted_keys, compositor_defs)[source]#

Supply the appropriate key in Store.options and supply suggestions for further completion.

classmethod option_completer(k, v)[source]#

Tab completion hook for the %%opts cell magic.

classmethod setup_completer()[source]#

Get the dictionary of valid completions

class holoviews.ipython.magics.OptsMagic(**kwargs: Any)[source]#

Bases: Magics

Magic for easy customising of normalization, plot and style options. Consult %%opts? for more information.

add_traits(**traits: Any) None[source]#

Dynamically add trait attributes to the HasTraits instance.

arg_err(func)[source]#

Print docstring if incorrect arguments were passed

classmethod class_config_rst_doc() str[source]#

Generate rST documentation for this class’ config options.

Excludes traits defined on parent classes.

classmethod class_config_section(classes: Sequence[type[HasTraits]] | None = None) str[source]#

Get the config section for this class.

Parameters#

classeslist, optional

The list of other classes in the config file. Used to reduce redundant information.

classmethod class_get_help(inst: HasTraits | None = None) str[source]#

Get the help string for this class in ReST format.

If inst is given, its current trait values will be used in place of class defaults.

classmethod class_get_trait_help(trait: TraitType[Any, Any], inst: HasTraits | None = None, helptext: str | None = None) str[source]#

Get the helptext string for a single trait.

Parameters:
  • inst – If given, its current trait values will be used in place of the class default.

  • helptext – If not given, uses the help attribute of the current trait.

classmethod class_own_trait_events(name: str) dict[str, EventHandler][source]#

Get a dict of all event handlers defined on this class, not a parent.

Works like event_handlers, except for excluding traits from parents.

classmethod class_own_traits(**metadata: Any) dict[str, TraitType[Any, Any]][source]#

Get a dict of all the traitlets defined on this class, not a parent.

Works like class_traits, except for excluding traits from parents.

classmethod class_print_help(inst: HasTraits | None = None) None[source]#

Get the help string for a single trait and print it.

classmethod class_trait_names(**metadata: Any) list[str][source]#

Get a list of all the names of this class’ traits.

This method is just like the trait_names() method, but is unbound.

classmethod class_traits(**metadata: Any) dict[str, TraitType[Any, Any]][source]#

Get a dict of all the traits of this class. The dictionary is keyed on the name and the values are the TraitType objects.

This method is just like the traits() method, but is unbound.

The TraitTypes returned don’t know anything about the values that the various HasTrait’s instances are holding.

The metadata kwargs allow functions to be passed in which filter traits based on metadata values. The functions should take a single value as an argument and return a boolean. If any function returns False, then the trait is not included in the output. If a metadata key doesn’t exist, None will be passed to the function.

property cross_validation_lock: Any#

A contextmanager for running a block with our cross validation lock set to True.

At the end of the block, the lock’s value is restored to its value prior to entering the block.

default_option(fn, optstr)[source]#

Make an entry in the options_table for fn, with value optstr

format_latex(strng)[source]#

Format a string for latex inclusion.

has_trait(name: str) bool[source]#

Returns True if the object has a trait with the specified name.

hold_trait_notifications() Any[source]#

Context manager for bundling trait change notifications and cross validation.

Use this when doing multiple trait assignments (init, config), to avoid race conditions in trait notifiers requesting other trait values. All trait notifications will fire after all values have been assigned.

notify_change(change: Bunch) None[source]#

Notify observers of a change event

observe(handler: Callable[[...], Any], names: Sentinel | str | Iterable[Sentinel | str] = traitlets.All, type: Sentinel | str = 'change') None[source]#

Setup a handler to be called when a trait changes.

This is used to setup dynamic notifications of trait changes.

Parameters#

handlercallable

A callable that is called when a trait changes. Its signature should be handler(change), where change is a dictionary. The change dictionary at least holds a ‘type’ key. * type: the type of notification. Other keys may be passed depending on the value of ‘type’. In the case where type is ‘change’, we also have the following keys: * owner : the HasTraits instance * old : the old value of the modified trait attribute * new : the new value of the modified trait attribute * name : the name of the modified trait attribute.

nameslist, str, All

If names is All, the handler will apply to all traits. If a list of str, handler will apply to all names in the list. If a str, the handler will apply just to that name.

typestr, All (default: ‘change’)

The type of notification to filter by. If equal to All, then all notifications are passed to the observe handler.

on_trait_change(handler: EventHandler | None = None, name: Sentinel | str | None = None, remove: bool = False) None[source]#

DEPRECATED: Setup a handler to be called when a trait changes.

This is used to setup dynamic notifications of trait changes.

Static handlers can be created by creating methods on a HasTraits subclass with the naming convention ‘_[traitname]_changed’. Thus, to create static handler for the trait ‘a’, create the method _a_changed(self, name, old, new) (fewer arguments can be used, see below).

If remove is True and handler is not specified, all change handlers for the specified name are uninstalled.

Parameters#

handlercallable, None

A callable that is called when a trait changes. Its signature can be handler(), handler(name), handler(name, new), handler(name, old, new), or handler(name, old, new, self).

namelist, str, None

If None, the handler will apply to all traits. If a list of str, handler will apply to all names in the list. If a str, the handler will apply just to that name.

removebool

If False (the default), then install the handler. If True then unintall it.

opts(line='', cell=None)[source]#

The opts line/cell magic with tab-completion.

%%opts [ [path] [normalization] [plotting options] [style options]]+

path: A dotted type.group.label specification

(e.g. Image.Grayscale.Photo)

normalization: List of normalization options delimited by braces.

One of | -axiswise | -framewise | +axiswise | +framewise | E.g. { +axiswise +framewise }

plotting options: List of plotting option keywords delimited by

square brackets. E.g. [show_title=False]

style options: List of style option keywords delimited by

parentheses. E.g. (lw=10 marker=’+’)

Note that commas between keywords are optional (not recommended) and that keywords must end in ‘=’ without a separating space.

More information may be found in the class docstring of util.parser.OptsSpec.

parse_options(arg_str, opt_str, *long_opts, **kw)[source]#

Parse options passed to an argument string.

The interface is similar to that of getopt.getopt(), but it returns a Struct with the options as keys and the stripped argument string still as a string.

arg_str is quoted as a true sys.argv vector by using shlex.split. This allows us to easily expand variables, glob files, quote arguments, etc.

Parameters#

arg_strstr

The arguments to parse.

opt_strstr

The options specification.

modestr, default ‘string’

If given as ‘list’, the argument string is returned as a list (split on whitespace) instead of a string.

list_allbool, default False

Put all option values in lists. Normally only options appearing more than once are put in a list.

posixbool, default True

Whether to split the input line in POSIX mode or not, as per the conventions outlined in the shlex module from the standard library.

classmethod process_element(obj)[source]#

To be called by the display hook which supplies the element to be displayed. Any customisation of the object can then occur before final display. If there is any error, a HTML message may be returned. If None is returned, display will proceed as normal.

classmethod section_names() list[str][source]#

return section names as a list

set_trait(name: str, value: Any) None[source]#

Forcibly sets trait attribute, including read-only attributes.

setup_instance(**kwargs: Any) None[source]#

This is called before self.__init__ is called.

trait_defaults(*names: str, **metadata: Any) dict[str, Any] | Sentinel[source]#

Return a trait’s default value or a dictionary of them

Notes#

Dynamically generated default values may depend on the current state of the object.

classmethod trait_events(name: str | None = None) dict[str, EventHandler][source]#

Get a dict of all the event handlers of this class.

Parameters#

namestr (default: None)

The name of a trait of this class. If name is None then all the event handlers of this class will be returned instead.

Returns#

The event handlers associated with a trait name, or all event handlers.

trait_has_value(name: str) bool[source]#

Returns True if the specified trait has a value.

This will return false even if getattr would return a dynamically generated default value. These default values will be recognized as existing only after they have been generated.

Example

class MyClass(HasTraits):
    i = Int()


mc = MyClass()
assert not mc.trait_has_value("i")
mc.i  # generates a default value
assert mc.trait_has_value("i")
trait_metadata(traitname: str, key: str, default: Any = None) Any[source]#

Get metadata values for trait by key.

trait_names(**metadata: Any) list[str][source]#

Get a list of all the names of this class’ traits.

trait_values(**metadata: Any) dict[str, Any][source]#

A dict of trait names and their values.

The metadata kwargs allow functions to be passed in which filter traits based on metadata values. The functions should take a single value as an argument and return a boolean. If any function returns False, then the trait is not included in the output. If a metadata key doesn’t exist, None will be passed to the function.

Returns#

A dict of trait names and their values.

Notes#

Trait values are retrieved via getattr, any exceptions raised by traits or the operations they may trigger will result in the absence of a trait value in the result dict.

traits(**metadata: Any) dict[str, TraitType[Any, Any]][source]#

Get a dict of all the traits of this class. The dictionary is keyed on the name and the values are the TraitType objects.

The TraitTypes returned don’t know anything about the values that the various HasTrait’s instances are holding.

The metadata kwargs allow functions to be passed in which filter traits based on metadata values. The functions should take a single value as an argument and return a boolean. If any function returns False, then the trait is not included in the output. If a metadata key doesn’t exist, None will be passed to the function.

unobserve(handler: Callable[[...], Any], names: Sentinel | str | Iterable[Sentinel | str] = traitlets.All, type: Sentinel | str = 'change') None[source]#

Remove a trait change handler.

This is used to unregister handlers to trait change notifications.

Parameters#

handlercallable

The callable called when a trait attribute changes.

nameslist, str, All (default: All)

The names of the traits for which the specified handler should be uninstalled. If names is All, the specified handler is uninstalled from the list of notifiers corresponding to all changes.

typestr or All (default: ‘change’)

The type of notification to filter by. If All, the specified handler is uninstalled from the list of notifiers corresponding to all types.

unobserve_all(name: str | Any = traitlets.All) None[source]#

Remove trait change handlers of any type for the specified name. If name is not specified, removes all trait notifiers.

update_config(config: Config) None[source]#

Update config and load the new values

class holoviews.ipython.magics.OutputMagic(**kwargs: Any)[source]#

Bases: Magics

add_traits(**traits: Any) None[source]#

Dynamically add trait attributes to the HasTraits instance.

arg_err(func)[source]#

Print docstring if incorrect arguments were passed

classmethod class_config_rst_doc() str[source]#

Generate rST documentation for this class’ config options.

Excludes traits defined on parent classes.

classmethod class_config_section(classes: Sequence[type[HasTraits]] | None = None) str[source]#

Get the config section for this class.

Parameters#

classeslist, optional

The list of other classes in the config file. Used to reduce redundant information.

classmethod class_get_help(inst: HasTraits | None = None) str[source]#

Get the help string for this class in ReST format.

If inst is given, its current trait values will be used in place of class defaults.

classmethod class_get_trait_help(trait: TraitType[Any, Any], inst: HasTraits | None = None, helptext: str | None = None) str[source]#

Get the helptext string for a single trait.

Parameters:
  • inst – If given, its current trait values will be used in place of the class default.

  • helptext – If not given, uses the help attribute of the current trait.

classmethod class_own_trait_events(name: str) dict[str, EventHandler][source]#

Get a dict of all event handlers defined on this class, not a parent.

Works like event_handlers, except for excluding traits from parents.

classmethod class_own_traits(**metadata: Any) dict[str, TraitType[Any, Any]][source]#

Get a dict of all the traitlets defined on this class, not a parent.

Works like class_traits, except for excluding traits from parents.

classmethod class_print_help(inst: HasTraits | None = None) None[source]#

Get the help string for a single trait and print it.

classmethod class_trait_names(**metadata: Any) list[str][source]#

Get a list of all the names of this class’ traits.

This method is just like the trait_names() method, but is unbound.

classmethod class_traits(**metadata: Any) dict[str, TraitType[Any, Any]][source]#

Get a dict of all the traits of this class. The dictionary is keyed on the name and the values are the TraitType objects.

This method is just like the traits() method, but is unbound.

The TraitTypes returned don’t know anything about the values that the various HasTrait’s instances are holding.

The metadata kwargs allow functions to be passed in which filter traits based on metadata values. The functions should take a single value as an argument and return a boolean. If any function returns False, then the trait is not included in the output. If a metadata key doesn’t exist, None will be passed to the function.

property cross_validation_lock: Any#

A contextmanager for running a block with our cross validation lock set to True.

At the end of the block, the lock’s value is restored to its value prior to entering the block.

default_option(fn, optstr)[source]#

Make an entry in the options_table for fn, with value optstr

format_latex(strng)[source]#

Format a string for latex inclusion.

has_trait(name: str) bool[source]#

Returns True if the object has a trait with the specified name.

hold_trait_notifications() Any[source]#

Context manager for bundling trait change notifications and cross validation.

Use this when doing multiple trait assignments (init, config), to avoid race conditions in trait notifiers requesting other trait values. All trait notifications will fire after all values have been assigned.

notify_change(change: Bunch) None[source]#

Notify observers of a change event

observe(handler: Callable[[...], Any], names: Sentinel | str | Iterable[Sentinel | str] = traitlets.All, type: Sentinel | str = 'change') None[source]#

Setup a handler to be called when a trait changes.

This is used to setup dynamic notifications of trait changes.

Parameters#

handlercallable

A callable that is called when a trait changes. Its signature should be handler(change), where change is a dictionary. The change dictionary at least holds a ‘type’ key. * type: the type of notification. Other keys may be passed depending on the value of ‘type’. In the case where type is ‘change’, we also have the following keys: * owner : the HasTraits instance * old : the old value of the modified trait attribute * new : the new value of the modified trait attribute * name : the name of the modified trait attribute.

nameslist, str, All

If names is All, the handler will apply to all traits. If a list of str, handler will apply to all names in the list. If a str, the handler will apply just to that name.

typestr, All (default: ‘change’)

The type of notification to filter by. If equal to All, then all notifications are passed to the observe handler.

on_trait_change(handler: EventHandler | None = None, name: Sentinel | str | None = None, remove: bool = False) None[source]#

DEPRECATED: Setup a handler to be called when a trait changes.

This is used to setup dynamic notifications of trait changes.

Static handlers can be created by creating methods on a HasTraits subclass with the naming convention ‘_[traitname]_changed’. Thus, to create static handler for the trait ‘a’, create the method _a_changed(self, name, old, new) (fewer arguments can be used, see below).

If remove is True and handler is not specified, all change handlers for the specified name are uninstalled.

Parameters#

handlercallable, None

A callable that is called when a trait changes. Its signature can be handler(), handler(name), handler(name, new), handler(name, old, new), or handler(name, old, new, self).

namelist, str, None

If None, the handler will apply to all traits. If a list of str, handler will apply to all names in the list. If a str, the handler will apply just to that name.

removebool

If False (the default), then install the handler. If True then unintall it.

parse_options(arg_str, opt_str, *long_opts, **kw)[source]#

Parse options passed to an argument string.

The interface is similar to that of getopt.getopt(), but it returns a Struct with the options as keys and the stripped argument string still as a string.

arg_str is quoted as a true sys.argv vector by using shlex.split. This allows us to easily expand variables, glob files, quote arguments, etc.

Parameters#

arg_strstr

The arguments to parse.

opt_strstr

The options specification.

modestr, default ‘string’

If given as ‘list’, the argument string is returned as a list (split on whitespace) instead of a string.

list_allbool, default False

Put all option values in lists. Normally only options appearing more than once are put in a list.

posixbool, default True

Whether to split the input line in POSIX mode or not, as per the conventions outlined in the shlex module from the standard library.

classmethod pprint()[source]#

Pretty print the current element options

classmethod section_names() list[str][source]#

return section names as a list

set_trait(name: str, value: Any) None[source]#

Forcibly sets trait attribute, including read-only attributes.

setup_instance(**kwargs: Any) None[source]#

This is called before self.__init__ is called.

trait_defaults(*names: str, **metadata: Any) dict[str, Any] | Sentinel[source]#

Return a trait’s default value or a dictionary of them

Notes#

Dynamically generated default values may depend on the current state of the object.

classmethod trait_events(name: str | None = None) dict[str, EventHandler][source]#

Get a dict of all the event handlers of this class.

Parameters#

namestr (default: None)

The name of a trait of this class. If name is None then all the event handlers of this class will be returned instead.

Returns#

The event handlers associated with a trait name, or all event handlers.

trait_has_value(name: str) bool[source]#

Returns True if the specified trait has a value.

This will return false even if getattr would return a dynamically generated default value. These default values will be recognized as existing only after they have been generated.

Example

class MyClass(HasTraits):
    i = Int()


mc = MyClass()
assert not mc.trait_has_value("i")
mc.i  # generates a default value
assert mc.trait_has_value("i")
trait_metadata(traitname: str, key: str, default: Any = None) Any[source]#

Get metadata values for trait by key.

trait_names(**metadata: Any) list[str][source]#

Get a list of all the names of this class’ traits.

trait_values(**metadata: Any) dict[str, Any][source]#

A dict of trait names and their values.

The metadata kwargs allow functions to be passed in which filter traits based on metadata values. The functions should take a single value as an argument and return a boolean. If any function returns False, then the trait is not included in the output. If a metadata key doesn’t exist, None will be passed to the function.

Returns#

A dict of trait names and their values.

Notes#

Trait values are retrieved via getattr, any exceptions raised by traits or the operations they may trigger will result in the absence of a trait value in the result dict.

traits(**metadata: Any) dict[str, TraitType[Any, Any]][source]#

Get a dict of all the traits of this class. The dictionary is keyed on the name and the values are the TraitType objects.

The TraitTypes returned don’t know anything about the values that the various HasTrait’s instances are holding.

The metadata kwargs allow functions to be passed in which filter traits based on metadata values. The functions should take a single value as an argument and return a boolean. If any function returns False, then the trait is not included in the output. If a metadata key doesn’t exist, None will be passed to the function.

unobserve(handler: Callable[[...], Any], names: Sentinel | str | Iterable[Sentinel | str] = traitlets.All, type: Sentinel | str = 'change') None[source]#

Remove a trait change handler.

This is used to unregister handlers to trait change notifications.

Parameters#

handlercallable

The callable called when a trait attribute changes.

nameslist, str, All (default: All)

The names of the traits for which the specified handler should be uninstalled. If names is All, the specified handler is uninstalled from the list of notifiers corresponding to all changes.

typestr or All (default: ‘change’)

The type of notification to filter by. If All, the specified handler is uninstalled from the list of notifiers corresponding to all types.

unobserve_all(name: str | Any = traitlets.All) None[source]#

Remove trait change handlers of any type for the specified name. If name is not specified, removes all trait notifiers.

update_config(config: Config) None[source]#

Update config and load the new values

class holoviews.ipython.magics.TimerMagic(**kwargs: Any)[source]#

Bases: Magics

A line magic for measuring the execution time of multiple cells.

After you start/reset the timer with ‘%timer start’ you may view elapsed time with any subsequent calls to %timer.

add_traits(**traits: Any) None[source]#

Dynamically add trait attributes to the HasTraits instance.

arg_err(func)[source]#

Print docstring if incorrect arguments were passed

classmethod class_config_rst_doc() str[source]#

Generate rST documentation for this class’ config options.

Excludes traits defined on parent classes.

classmethod class_config_section(classes: Sequence[type[HasTraits]] | None = None) str[source]#

Get the config section for this class.

Parameters#

classeslist, optional

The list of other classes in the config file. Used to reduce redundant information.

classmethod class_get_help(inst: HasTraits | None = None) str[source]#

Get the help string for this class in ReST format.

If inst is given, its current trait values will be used in place of class defaults.

classmethod class_get_trait_help(trait: TraitType[Any, Any], inst: HasTraits | None = None, helptext: str | None = None) str[source]#

Get the helptext string for a single trait.

Parameters:
  • inst – If given, its current trait values will be used in place of the class default.

  • helptext – If not given, uses the help attribute of the current trait.

classmethod class_own_trait_events(name: str) dict[str, EventHandler][source]#

Get a dict of all event handlers defined on this class, not a parent.

Works like event_handlers, except for excluding traits from parents.

classmethod class_own_traits(**metadata: Any) dict[str, TraitType[Any, Any]][source]#

Get a dict of all the traitlets defined on this class, not a parent.

Works like class_traits, except for excluding traits from parents.

classmethod class_print_help(inst: HasTraits | None = None) None[source]#

Get the help string for a single trait and print it.

classmethod class_trait_names(**metadata: Any) list[str][source]#

Get a list of all the names of this class’ traits.

This method is just like the trait_names() method, but is unbound.

classmethod class_traits(**metadata: Any) dict[str, TraitType[Any, Any]][source]#

Get a dict of all the traits of this class. The dictionary is keyed on the name and the values are the TraitType objects.

This method is just like the traits() method, but is unbound.

The TraitTypes returned don’t know anything about the values that the various HasTrait’s instances are holding.

The metadata kwargs allow functions to be passed in which filter traits based on metadata values. The functions should take a single value as an argument and return a boolean. If any function returns False, then the trait is not included in the output. If a metadata key doesn’t exist, None will be passed to the function.

property cross_validation_lock: Any#

A contextmanager for running a block with our cross validation lock set to True.

At the end of the block, the lock’s value is restored to its value prior to entering the block.

default_option(fn, optstr)[source]#

Make an entry in the options_table for fn, with value optstr

format_latex(strng)[source]#

Format a string for latex inclusion.

has_trait(name: str) bool[source]#

Returns True if the object has a trait with the specified name.

hold_trait_notifications() Any[source]#

Context manager for bundling trait change notifications and cross validation.

Use this when doing multiple trait assignments (init, config), to avoid race conditions in trait notifiers requesting other trait values. All trait notifications will fire after all values have been assigned.

notify_change(change: Bunch) None[source]#

Notify observers of a change event

observe(handler: Callable[[...], Any], names: Sentinel | str | Iterable[Sentinel | str] = traitlets.All, type: Sentinel | str = 'change') None[source]#

Setup a handler to be called when a trait changes.

This is used to setup dynamic notifications of trait changes.

Parameters#

handlercallable

A callable that is called when a trait changes. Its signature should be handler(change), where change is a dictionary. The change dictionary at least holds a ‘type’ key. * type: the type of notification. Other keys may be passed depending on the value of ‘type’. In the case where type is ‘change’, we also have the following keys: * owner : the HasTraits instance * old : the old value of the modified trait attribute * new : the new value of the modified trait attribute * name : the name of the modified trait attribute.

nameslist, str, All

If names is All, the handler will apply to all traits. If a list of str, handler will apply to all names in the list. If a str, the handler will apply just to that name.

typestr, All (default: ‘change’)

The type of notification to filter by. If equal to All, then all notifications are passed to the observe handler.

on_trait_change(handler: EventHandler | None = None, name: Sentinel | str | None = None, remove: bool = False) None[source]#

DEPRECATED: Setup a handler to be called when a trait changes.

This is used to setup dynamic notifications of trait changes.

Static handlers can be created by creating methods on a HasTraits subclass with the naming convention ‘_[traitname]_changed’. Thus, to create static handler for the trait ‘a’, create the method _a_changed(self, name, old, new) (fewer arguments can be used, see below).

If remove is True and handler is not specified, all change handlers for the specified name are uninstalled.

Parameters#

handlercallable, None

A callable that is called when a trait changes. Its signature can be handler(), handler(name), handler(name, new), handler(name, old, new), or handler(name, old, new, self).

namelist, str, None

If None, the handler will apply to all traits. If a list of str, handler will apply to all names in the list. If a str, the handler will apply just to that name.

removebool

If False (the default), then install the handler. If True then unintall it.

parse_options(arg_str, opt_str, *long_opts, **kw)[source]#

Parse options passed to an argument string.

The interface is similar to that of getopt.getopt(), but it returns a Struct with the options as keys and the stripped argument string still as a string.

arg_str is quoted as a true sys.argv vector by using shlex.split. This allows us to easily expand variables, glob files, quote arguments, etc.

Parameters#

arg_strstr

The arguments to parse.

opt_strstr

The options specification.

modestr, default ‘string’

If given as ‘list’, the argument string is returned as a list (split on whitespace) instead of a string.

list_allbool, default False

Put all option values in lists. Normally only options appearing more than once are put in a list.

posixbool, default True

Whether to split the input line in POSIX mode or not, as per the conventions outlined in the shlex module from the standard library.

classmethod section_names() list[str][source]#

return section names as a list

set_trait(name: str, value: Any) None[source]#

Forcibly sets trait attribute, including read-only attributes.

setup_instance(**kwargs: Any) None[source]#

This is called before self.__init__ is called.

timer(line='')[source]#

Timer magic to print initial date/time information and subsequent elapsed time intervals.

To start the timer, run:

%timer start

This will print the start date and time.

Subsequent calls to %timer will print the elapsed time relative to the time when %timer start was called. Subsequent calls to %timer start may also be used to reset the timer.

trait_defaults(*names: str, **metadata: Any) dict[str, Any] | Sentinel[source]#

Return a trait’s default value or a dictionary of them

Notes#

Dynamically generated default values may depend on the current state of the object.

classmethod trait_events(name: str | None = None) dict[str, EventHandler][source]#

Get a dict of all the event handlers of this class.

Parameters#

namestr (default: None)

The name of a trait of this class. If name is None then all the event handlers of this class will be returned instead.

Returns#

The event handlers associated with a trait name, or all event handlers.

trait_has_value(name: str) bool[source]#

Returns True if the specified trait has a value.

This will return false even if getattr would return a dynamically generated default value. These default values will be recognized as existing only after they have been generated.

Example

class MyClass(HasTraits):
    i = Int()


mc = MyClass()
assert not mc.trait_has_value("i")
mc.i  # generates a default value
assert mc.trait_has_value("i")
trait_metadata(traitname: str, key: str, default: Any = None) Any[source]#

Get metadata values for trait by key.

trait_names(**metadata: Any) list[str][source]#

Get a list of all the names of this class’ traits.

trait_values(**metadata: Any) dict[str, Any][source]#

A dict of trait names and their values.

The metadata kwargs allow functions to be passed in which filter traits based on metadata values. The functions should take a single value as an argument and return a boolean. If any function returns False, then the trait is not included in the output. If a metadata key doesn’t exist, None will be passed to the function.

Returns#

A dict of trait names and their values.

Notes#

Trait values are retrieved via getattr, any exceptions raised by traits or the operations they may trigger will result in the absence of a trait value in the result dict.

traits(**metadata: Any) dict[str, TraitType[Any, Any]][source]#

Get a dict of all the traits of this class. The dictionary is keyed on the name and the values are the TraitType objects.

The TraitTypes returned don’t know anything about the values that the various HasTrait’s instances are holding.

The metadata kwargs allow functions to be passed in which filter traits based on metadata values. The functions should take a single value as an argument and return a boolean. If any function returns False, then the trait is not included in the output. If a metadata key doesn’t exist, None will be passed to the function.

unobserve(handler: Callable[[...], Any], names: Sentinel | str | Iterable[Sentinel | str] = traitlets.All, type: Sentinel | str = 'change') None[source]#

Remove a trait change handler.

This is used to unregister handlers to trait change notifications.

Parameters#

handlercallable

The callable called when a trait attribute changes.

nameslist, str, All (default: All)

The names of the traits for which the specified handler should be uninstalled. If names is All, the specified handler is uninstalled from the list of notifiers corresponding to all changes.

typestr or All (default: ‘change’)

The type of notification to filter by. If All, the specified handler is uninstalled from the list of notifiers corresponding to all types.

unobserve_all(name: str | Any = traitlets.All) None[source]#

Remove trait change handlers of any type for the specified name. If name is not specified, removes all trait notifiers.

update_config(config: Config) None[source]#

Update config and load the new values


preprocessors Module#

Prototype demo:

python holoviews/ipython/convert.py Conversion_Example.ipynb | python

class holoviews.ipython.preprocessors.OptsMagicProcessor(**kwargs: Any)[source]#

Bases: Preprocessor

Preprocessor to convert notebooks to Python source to convert use of opts magic to use the util.opts utility instead.

add_traits(**traits: Any) None[source]#

Dynamically add trait attributes to the HasTraits instance.

classmethod class_config_rst_doc() str[source]#

Generate rST documentation for this class’ config options.

Excludes traits defined on parent classes.

classmethod class_config_section(classes: Sequence[type[HasTraits]] | None = None) str[source]#

Get the config section for this class.

Parameters#

classeslist, optional

The list of other classes in the config file. Used to reduce redundant information.

classmethod class_get_help(inst: HasTraits | None = None) str[source]#

Get the help string for this class in ReST format.

If inst is given, its current trait values will be used in place of class defaults.

classmethod class_get_trait_help(trait: TraitType[Any, Any], inst: HasTraits | None = None, helptext: str | None = None) str[source]#

Get the helptext string for a single trait.

Parameters:
  • inst – If given, its current trait values will be used in place of the class default.

  • helptext – If not given, uses the help attribute of the current trait.

classmethod class_own_trait_events(name: str) dict[str, EventHandler][source]#

Get a dict of all event handlers defined on this class, not a parent.

Works like event_handlers, except for excluding traits from parents.

classmethod class_own_traits(**metadata: Any) dict[str, TraitType[Any, Any]][source]#

Get a dict of all the traitlets defined on this class, not a parent.

Works like class_traits, except for excluding traits from parents.

classmethod class_print_help(inst: HasTraits | None = None) None[source]#

Get the help string for a single trait and print it.

classmethod class_trait_names(**metadata: Any) list[str][source]#

Get a list of all the names of this class’ traits.

This method is just like the trait_names() method, but is unbound.

classmethod class_traits(**metadata: Any) dict[str, TraitType[Any, Any]][source]#

Get a dict of all the traits of this class. The dictionary is keyed on the name and the values are the TraitType objects.

This method is just like the traits() method, but is unbound.

The TraitTypes returned don’t know anything about the values that the various HasTrait’s instances are holding.

The metadata kwargs allow functions to be passed in which filter traits based on metadata values. The functions should take a single value as an argument and return a boolean. If any function returns False, then the trait is not included in the output. If a metadata key doesn’t exist, None will be passed to the function.

property cross_validation_lock: Any#

A contextmanager for running a block with our cross validation lock set to True.

At the end of the block, the lock’s value is restored to its value prior to entering the block.

default_language#

Deprecated default highlight language as of 5.0, please use language_info metadata instead

display_data_priority#

An ordered list of preferred output type, the first encountered will usually be used when converting discarding the others.

has_trait(name: str) bool[source]#

Returns True if the object has a trait with the specified name.

hold_trait_notifications() Any[source]#

Context manager for bundling trait change notifications and cross validation.

Use this when doing multiple trait assignments (init, config), to avoid race conditions in trait notifiers requesting other trait values. All trait notifications will fire after all values have been assigned.

log#

Logger or LoggerAdapter instance

notify_change(change: Bunch) None[source]#

Notify observers of a change event

observe(handler: Callable[[...], Any], names: Sentinel | str | Iterable[Sentinel | str] = traitlets.All, type: Sentinel | str = 'change') None[source]#

Setup a handler to be called when a trait changes.

This is used to setup dynamic notifications of trait changes.

Parameters#

handlercallable

A callable that is called when a trait changes. Its signature should be handler(change), where change is a dictionary. The change dictionary at least holds a ‘type’ key. * type: the type of notification. Other keys may be passed depending on the value of ‘type’. In the case where type is ‘change’, we also have the following keys: * owner : the HasTraits instance * old : the old value of the modified trait attribute * new : the new value of the modified trait attribute * name : the name of the modified trait attribute.

nameslist, str, All

If names is All, the handler will apply to all traits. If a list of str, handler will apply to all names in the list. If a str, the handler will apply just to that name.

typestr, All (default: ‘change’)

The type of notification to filter by. If equal to All, then all notifications are passed to the observe handler.

on_trait_change(handler: EventHandler | None = None, name: Sentinel | str | None = None, remove: bool = False) None[source]#

DEPRECATED: Setup a handler to be called when a trait changes.

This is used to setup dynamic notifications of trait changes.

Static handlers can be created by creating methods on a HasTraits subclass with the naming convention ‘_[traitname]_changed’. Thus, to create static handler for the trait ‘a’, create the method _a_changed(self, name, old, new) (fewer arguments can be used, see below).

If remove is True and handler is not specified, all change handlers for the specified name are uninstalled.

Parameters#

handlercallable, None

A callable that is called when a trait changes. Its signature can be handler(), handler(name), handler(name, new), handler(name, old, new), or handler(name, old, new, self).

namelist, str, None

If None, the handler will apply to all traits. If a list of str, handler will apply to all names in the list. If a str, the handler will apply just to that name.

removebool

If False (the default), then install the handler. If True then unintall it.

preprocess(nb, resources)[source]#

Preprocessing to apply on each notebook.

Must return modified nb, resources.

If you wish to apply your preprocessing to each cell, you might want to override preprocess_cell method instead.

Parameters#

nbNotebookNode

Notebook being converted

resourcesdictionary

Additional resources used in the conversion process. Allows preprocessors to pass variables into the Jinja engine.

preprocess_cell(cell, resources, index)[source]#

Override if you want to apply some preprocessing to each cell. Must return modified cell and resource dictionary.

Parameters#

cellNotebookNode cell

Notebook cell being processed

resourcesdictionary

Additional resources used in the conversion process. Allows preprocessors to pass variables into the Jinja engine.

indexint

Index of the cell being processed

classmethod section_names() list[str][source]#

return section names as a list

set_trait(name: str, value: Any) None[source]#

Forcibly sets trait attribute, including read-only attributes.

setup_instance(**kwargs: Any) None[source]#

This is called before self.__init__ is called.

trait_defaults(*names: str, **metadata: Any) dict[str, Any] | Sentinel[source]#

Return a trait’s default value or a dictionary of them

Notes#

Dynamically generated default values may depend on the current state of the object.

classmethod trait_events(name: str | None = None) dict[str, EventHandler][source]#

Get a dict of all the event handlers of this class.

Parameters#

namestr (default: None)

The name of a trait of this class. If name is None then all the event handlers of this class will be returned instead.

Returns#

The event handlers associated with a trait name, or all event handlers.

trait_has_value(name: str) bool[source]#

Returns True if the specified trait has a value.

This will return false even if getattr would return a dynamically generated default value. These default values will be recognized as existing only after they have been generated.

Example

class MyClass(HasTraits):
    i = Int()


mc = MyClass()
assert not mc.trait_has_value("i")
mc.i  # generates a default value
assert mc.trait_has_value("i")
trait_metadata(traitname: str, key: str, default: Any = None) Any[source]#

Get metadata values for trait by key.

trait_names(**metadata: Any) list[str][source]#

Get a list of all the names of this class’ traits.

trait_values(**metadata: Any) dict[str, Any][source]#

A dict of trait names and their values.

The metadata kwargs allow functions to be passed in which filter traits based on metadata values. The functions should take a single value as an argument and return a boolean. If any function returns False, then the trait is not included in the output. If a metadata key doesn’t exist, None will be passed to the function.

Returns#

A dict of trait names and their values.

Notes#

Trait values are retrieved via getattr, any exceptions raised by traits or the operations they may trigger will result in the absence of a trait value in the result dict.

traits(**metadata: Any) dict[str, TraitType[Any, Any]][source]#

Get a dict of all the traits of this class. The dictionary is keyed on the name and the values are the TraitType objects.

The TraitTypes returned don’t know anything about the values that the various HasTrait’s instances are holding.

The metadata kwargs allow functions to be passed in which filter traits based on metadata values. The functions should take a single value as an argument and return a boolean. If any function returns False, then the trait is not included in the output. If a metadata key doesn’t exist, None will be passed to the function.

unobserve(handler: Callable[[...], Any], names: Sentinel | str | Iterable[Sentinel | str] = traitlets.All, type: Sentinel | str = 'change') None[source]#

Remove a trait change handler.

This is used to unregister handlers to trait change notifications.

Parameters#

handlercallable

The callable called when a trait attribute changes.

nameslist, str, All (default: All)

The names of the traits for which the specified handler should be uninstalled. If names is All, the specified handler is uninstalled from the list of notifiers corresponding to all changes.

typestr or All (default: ‘change’)

The type of notification to filter by. If All, the specified handler is uninstalled from the list of notifiers corresponding to all types.

unobserve_all(name: str | Any = traitlets.All) None[source]#

Remove trait change handlers of any type for the specified name. If name is not specified, removes all trait notifiers.

update_config(config: Config) None[source]#

Update config and load the new values

class holoviews.ipython.preprocessors.OutputMagicProcessor(**kwargs: Any)[source]#

Bases: Preprocessor

Preprocessor to convert notebooks to Python source to convert use of output magic to use the util.output utility instead.

add_traits(**traits: Any) None[source]#

Dynamically add trait attributes to the HasTraits instance.

classmethod class_config_rst_doc() str[source]#

Generate rST documentation for this class’ config options.

Excludes traits defined on parent classes.

classmethod class_config_section(classes: Sequence[type[HasTraits]] | None = None) str[source]#

Get the config section for this class.

Parameters#

classeslist, optional

The list of other classes in the config file. Used to reduce redundant information.

classmethod class_get_help(inst: HasTraits | None = None) str[source]#

Get the help string for this class in ReST format.

If inst is given, its current trait values will be used in place of class defaults.

classmethod class_get_trait_help(trait: TraitType[Any, Any], inst: HasTraits | None = None, helptext: str | None = None) str[source]#

Get the helptext string for a single trait.

Parameters:
  • inst – If given, its current trait values will be used in place of the class default.

  • helptext – If not given, uses the help attribute of the current trait.

classmethod class_own_trait_events(name: str) dict[str, EventHandler][source]#

Get a dict of all event handlers defined on this class, not a parent.

Works like event_handlers, except for excluding traits from parents.

classmethod class_own_traits(**metadata: Any) dict[str, TraitType[Any, Any]][source]#

Get a dict of all the traitlets defined on this class, not a parent.

Works like class_traits, except for excluding traits from parents.

classmethod class_print_help(inst: HasTraits | None = None) None[source]#

Get the help string for a single trait and print it.

classmethod class_trait_names(**metadata: Any) list[str][source]#

Get a list of all the names of this class’ traits.

This method is just like the trait_names() method, but is unbound.

classmethod class_traits(**metadata: Any) dict[str, TraitType[Any, Any]][source]#

Get a dict of all the traits of this class. The dictionary is keyed on the name and the values are the TraitType objects.

This method is just like the traits() method, but is unbound.

The TraitTypes returned don’t know anything about the values that the various HasTrait’s instances are holding.

The metadata kwargs allow functions to be passed in which filter traits based on metadata values. The functions should take a single value as an argument and return a boolean. If any function returns False, then the trait is not included in the output. If a metadata key doesn’t exist, None will be passed to the function.

property cross_validation_lock: Any#

A contextmanager for running a block with our cross validation lock set to True.

At the end of the block, the lock’s value is restored to its value prior to entering the block.

default_language#

Deprecated default highlight language as of 5.0, please use language_info metadata instead

display_data_priority#

An ordered list of preferred output type, the first encountered will usually be used when converting discarding the others.

has_trait(name: str) bool[source]#

Returns True if the object has a trait with the specified name.

hold_trait_notifications() Any[source]#

Context manager for bundling trait change notifications and cross validation.

Use this when doing multiple trait assignments (init, config), to avoid race conditions in trait notifiers requesting other trait values. All trait notifications will fire after all values have been assigned.

log#

Logger or LoggerAdapter instance

notify_change(change: Bunch) None[source]#

Notify observers of a change event

observe(handler: Callable[[...], Any], names: Sentinel | str | Iterable[Sentinel | str] = traitlets.All, type: Sentinel | str = 'change') None[source]#

Setup a handler to be called when a trait changes.

This is used to setup dynamic notifications of trait changes.

Parameters#

handlercallable

A callable that is called when a trait changes. Its signature should be handler(change), where change is a dictionary. The change dictionary at least holds a ‘type’ key. * type: the type of notification. Other keys may be passed depending on the value of ‘type’. In the case where type is ‘change’, we also have the following keys: * owner : the HasTraits instance * old : the old value of the modified trait attribute * new : the new value of the modified trait attribute * name : the name of the modified trait attribute.

nameslist, str, All

If names is All, the handler will apply to all traits. If a list of str, handler will apply to all names in the list. If a str, the handler will apply just to that name.

typestr, All (default: ‘change’)

The type of notification to filter by. If equal to All, then all notifications are passed to the observe handler.

on_trait_change(handler: EventHandler | None = None, name: Sentinel | str | None = None, remove: bool = False) None[source]#

DEPRECATED: Setup a handler to be called when a trait changes.

This is used to setup dynamic notifications of trait changes.

Static handlers can be created by creating methods on a HasTraits subclass with the naming convention ‘_[traitname]_changed’. Thus, to create static handler for the trait ‘a’, create the method _a_changed(self, name, old, new) (fewer arguments can be used, see below).

If remove is True and handler is not specified, all change handlers for the specified name are uninstalled.

Parameters#

handlercallable, None

A callable that is called when a trait changes. Its signature can be handler(), handler(name), handler(name, new), handler(name, old, new), or handler(name, old, new, self).

namelist, str, None

If None, the handler will apply to all traits. If a list of str, handler will apply to all names in the list. If a str, the handler will apply just to that name.

removebool

If False (the default), then install the handler. If True then unintall it.

preprocess(nb, resources)[source]#

Preprocessing to apply on each notebook.

Must return modified nb, resources.

If you wish to apply your preprocessing to each cell, you might want to override preprocess_cell method instead.

Parameters#

nbNotebookNode

Notebook being converted

resourcesdictionary

Additional resources used in the conversion process. Allows preprocessors to pass variables into the Jinja engine.

preprocess_cell(cell, resources, index)[source]#

Override if you want to apply some preprocessing to each cell. Must return modified cell and resource dictionary.

Parameters#

cellNotebookNode cell

Notebook cell being processed

resourcesdictionary

Additional resources used in the conversion process. Allows preprocessors to pass variables into the Jinja engine.

indexint

Index of the cell being processed

classmethod section_names() list[str][source]#

return section names as a list

set_trait(name: str, value: Any) None[source]#

Forcibly sets trait attribute, including read-only attributes.

setup_instance(**kwargs: Any) None[source]#

This is called before self.__init__ is called.

trait_defaults(*names: str, **metadata: Any) dict[str, Any] | Sentinel[source]#

Return a trait’s default value or a dictionary of them

Notes#

Dynamically generated default values may depend on the current state of the object.

classmethod trait_events(name: str | None = None) dict[str, EventHandler][source]#

Get a dict of all the event handlers of this class.

Parameters#

namestr (default: None)

The name of a trait of this class. If name is None then all the event handlers of this class will be returned instead.

Returns#

The event handlers associated with a trait name, or all event handlers.

trait_has_value(name: str) bool[source]#

Returns True if the specified trait has a value.

This will return false even if getattr would return a dynamically generated default value. These default values will be recognized as existing only after they have been generated.

Example

class MyClass(HasTraits):
    i = Int()


mc = MyClass()
assert not mc.trait_has_value("i")
mc.i  # generates a default value
assert mc.trait_has_value("i")
trait_metadata(traitname: str, key: str, default: Any = None) Any[source]#

Get metadata values for trait by key.

trait_names(**metadata: Any) list[str][source]#

Get a list of all the names of this class’ traits.

trait_values(**metadata: Any) dict[str, Any][source]#

A dict of trait names and their values.

The metadata kwargs allow functions to be passed in which filter traits based on metadata values. The functions should take a single value as an argument and return a boolean. If any function returns False, then the trait is not included in the output. If a metadata key doesn’t exist, None will be passed to the function.

Returns#

A dict of trait names and their values.

Notes#

Trait values are retrieved via getattr, any exceptions raised by traits or the operations they may trigger will result in the absence of a trait value in the result dict.

traits(**metadata: Any) dict[str, TraitType[Any, Any]][source]#

Get a dict of all the traits of this class. The dictionary is keyed on the name and the values are the TraitType objects.

The TraitTypes returned don’t know anything about the values that the various HasTrait’s instances are holding.

The metadata kwargs allow functions to be passed in which filter traits based on metadata values. The functions should take a single value as an argument and return a boolean. If any function returns False, then the trait is not included in the output. If a metadata key doesn’t exist, None will be passed to the function.

unobserve(handler: Callable[[...], Any], names: Sentinel | str | Iterable[Sentinel | str] = traitlets.All, type: Sentinel | str = 'change') None[source]#

Remove a trait change handler.

This is used to unregister handlers to trait change notifications.

Parameters#

handlercallable

The callable called when a trait attribute changes.

nameslist, str, All (default: All)

The names of the traits for which the specified handler should be uninstalled. If names is All, the specified handler is uninstalled from the list of notifiers corresponding to all changes.

typestr or All (default: ‘change’)

The type of notification to filter by. If All, the specified handler is uninstalled from the list of notifiers corresponding to all types.

unobserve_all(name: str | Any = traitlets.All) None[source]#

Remove trait change handlers of any type for the specified name. If name is not specified, removes all trait notifiers.

update_config(config: Config) None[source]#

Update config and load the new values

class holoviews.ipython.preprocessors.StripMagicsProcessor(**kwargs: Any)[source]#

Bases: Preprocessor

Preprocessor to convert notebooks to Python source to strips out all magics. To be applied after the preprocessors that can handle holoviews magics appropriately.

add_traits(**traits: Any) None[source]#

Dynamically add trait attributes to the HasTraits instance.

classmethod class_config_rst_doc() str[source]#

Generate rST documentation for this class’ config options.

Excludes traits defined on parent classes.

classmethod class_config_section(classes: Sequence[type[HasTraits]] | None = None) str[source]#

Get the config section for this class.

Parameters#

classeslist, optional

The list of other classes in the config file. Used to reduce redundant information.

classmethod class_get_help(inst: HasTraits | None = None) str[source]#

Get the help string for this class in ReST format.

If inst is given, its current trait values will be used in place of class defaults.

classmethod class_get_trait_help(trait: TraitType[Any, Any], inst: HasTraits | None = None, helptext: str | None = None) str[source]#

Get the helptext string for a single trait.

Parameters:
  • inst – If given, its current trait values will be used in place of the class default.

  • helptext – If not given, uses the help attribute of the current trait.

classmethod class_own_trait_events(name: str) dict[str, EventHandler][source]#

Get a dict of all event handlers defined on this class, not a parent.

Works like event_handlers, except for excluding traits from parents.

classmethod class_own_traits(**metadata: Any) dict[str, TraitType[Any, Any]][source]#

Get a dict of all the traitlets defined on this class, not a parent.

Works like class_traits, except for excluding traits from parents.

classmethod class_print_help(inst: HasTraits | None = None) None[source]#

Get the help string for a single trait and print it.

classmethod class_trait_names(**metadata: Any) list[str][source]#

Get a list of all the names of this class’ traits.

This method is just like the trait_names() method, but is unbound.

classmethod class_traits(**metadata: Any) dict[str, TraitType[Any, Any]][source]#

Get a dict of all the traits of this class. The dictionary is keyed on the name and the values are the TraitType objects.

This method is just like the traits() method, but is unbound.

The TraitTypes returned don’t know anything about the values that the various HasTrait’s instances are holding.

The metadata kwargs allow functions to be passed in which filter traits based on metadata values. The functions should take a single value as an argument and return a boolean. If any function returns False, then the trait is not included in the output. If a metadata key doesn’t exist, None will be passed to the function.

property cross_validation_lock: Any#

A contextmanager for running a block with our cross validation lock set to True.

At the end of the block, the lock’s value is restored to its value prior to entering the block.

default_language#

Deprecated default highlight language as of 5.0, please use language_info metadata instead

display_data_priority#

An ordered list of preferred output type, the first encountered will usually be used when converting discarding the others.

has_trait(name: str) bool[source]#

Returns True if the object has a trait with the specified name.

hold_trait_notifications() Any[source]#

Context manager for bundling trait change notifications and cross validation.

Use this when doing multiple trait assignments (init, config), to avoid race conditions in trait notifiers requesting other trait values. All trait notifications will fire after all values have been assigned.

log#

Logger or LoggerAdapter instance

notify_change(change: Bunch) None[source]#

Notify observers of a change event

observe(handler: Callable[[...], Any], names: Sentinel | str | Iterable[Sentinel | str] = traitlets.All, type: Sentinel | str = 'change') None[source]#

Setup a handler to be called when a trait changes.

This is used to setup dynamic notifications of trait changes.

Parameters#

handlercallable

A callable that is called when a trait changes. Its signature should be handler(change), where change is a dictionary. The change dictionary at least holds a ‘type’ key. * type: the type of notification. Other keys may be passed depending on the value of ‘type’. In the case where type is ‘change’, we also have the following keys: * owner : the HasTraits instance * old : the old value of the modified trait attribute * new : the new value of the modified trait attribute * name : the name of the modified trait attribute.

nameslist, str, All

If names is All, the handler will apply to all traits. If a list of str, handler will apply to all names in the list. If a str, the handler will apply just to that name.

typestr, All (default: ‘change’)

The type of notification to filter by. If equal to All, then all notifications are passed to the observe handler.

on_trait_change(handler: EventHandler | None = None, name: Sentinel | str | None = None, remove: bool = False) None[source]#

DEPRECATED: Setup a handler to be called when a trait changes.

This is used to setup dynamic notifications of trait changes.

Static handlers can be created by creating methods on a HasTraits subclass with the naming convention ‘_[traitname]_changed’. Thus, to create static handler for the trait ‘a’, create the method _a_changed(self, name, old, new) (fewer arguments can be used, see below).

If remove is True and handler is not specified, all change handlers for the specified name are uninstalled.

Parameters#

handlercallable, None

A callable that is called when a trait changes. Its signature can be handler(), handler(name), handler(name, new), handler(name, old, new), or handler(name, old, new, self).

namelist, str, None

If None, the handler will apply to all traits. If a list of str, handler will apply to all names in the list. If a str, the handler will apply just to that name.

removebool

If False (the default), then install the handler. If True then unintall it.

preprocess(nb, resources)[source]#

Preprocessing to apply on each notebook.

Must return modified nb, resources.

If you wish to apply your preprocessing to each cell, you might want to override preprocess_cell method instead.

Parameters#

nbNotebookNode

Notebook being converted

resourcesdictionary

Additional resources used in the conversion process. Allows preprocessors to pass variables into the Jinja engine.

preprocess_cell(cell, resources, index)[source]#

Override if you want to apply some preprocessing to each cell. Must return modified cell and resource dictionary.

Parameters#

cellNotebookNode cell

Notebook cell being processed

resourcesdictionary

Additional resources used in the conversion process. Allows preprocessors to pass variables into the Jinja engine.

indexint

Index of the cell being processed

classmethod section_names() list[str][source]#

return section names as a list

set_trait(name: str, value: Any) None[source]#

Forcibly sets trait attribute, including read-only attributes.

setup_instance(**kwargs: Any) None[source]#

This is called before self.__init__ is called.

trait_defaults(*names: str, **metadata: Any) dict[str, Any] | Sentinel[source]#

Return a trait’s default value or a dictionary of them

Notes#

Dynamically generated default values may depend on the current state of the object.

classmethod trait_events(name: str | None = None) dict[str, EventHandler][source]#

Get a dict of all the event handlers of this class.

Parameters#

namestr (default: None)

The name of a trait of this class. If name is None then all the event handlers of this class will be returned instead.

Returns#

The event handlers associated with a trait name, or all event handlers.

trait_has_value(name: str) bool[source]#

Returns True if the specified trait has a value.

This will return false even if getattr would return a dynamically generated default value. These default values will be recognized as existing only after they have been generated.

Example

class MyClass(HasTraits):
    i = Int()


mc = MyClass()
assert not mc.trait_has_value("i")
mc.i  # generates a default value
assert mc.trait_has_value("i")
trait_metadata(traitname: str, key: str, default: Any = None) Any[source]#

Get metadata values for trait by key.

trait_names(**metadata: Any) list[str][source]#

Get a list of all the names of this class’ traits.

trait_values(**metadata: Any) dict[str, Any][source]#

A dict of trait names and their values.

The metadata kwargs allow functions to be passed in which filter traits based on metadata values. The functions should take a single value as an argument and return a boolean. If any function returns False, then the trait is not included in the output. If a metadata key doesn’t exist, None will be passed to the function.

Returns#

A dict of trait names and their values.

Notes#

Trait values are retrieved via getattr, any exceptions raised by traits or the operations they may trigger will result in the absence of a trait value in the result dict.

traits(**metadata: Any) dict[str, TraitType[Any, Any]][source]#

Get a dict of all the traits of this class. The dictionary is keyed on the name and the values are the TraitType objects.

The TraitTypes returned don’t know anything about the values that the various HasTrait’s instances are holding.

The metadata kwargs allow functions to be passed in which filter traits based on metadata values. The functions should take a single value as an argument and return a boolean. If any function returns False, then the trait is not included in the output. If a metadata key doesn’t exist, None will be passed to the function.

unobserve(handler: Callable[[...], Any], names: Sentinel | str | Iterable[Sentinel | str] = traitlets.All, type: Sentinel | str = 'change') None[source]#

Remove a trait change handler.

This is used to unregister handlers to trait change notifications.

Parameters#

handlercallable

The callable called when a trait attribute changes.

nameslist, str, All (default: All)

The names of the traits for which the specified handler should be uninstalled. If names is All, the specified handler is uninstalled from the list of notifiers corresponding to all changes.

typestr or All (default: ‘change’)

The type of notification to filter by. If All, the specified handler is uninstalled from the list of notifiers corresponding to all types.

unobserve_all(name: str | Any = traitlets.All) None[source]#

Remove trait change handlers of any type for the specified name. If name is not specified, removes all trait notifiers.

update_config(config: Config) None[source]#

Update config and load the new values

class holoviews.ipython.preprocessors.Substitute(**kwargs: Any)[source]#

Bases: Preprocessor

An nbconvert preprocessor that substitutes one set of HTML data output for another, adding annotation to the output as required.

The constructor accepts the notebook format version and a substitutions dictionary:

{source_html:(target_html, annotation)}

Where the annotation may be None (i.e. no annotation).

add_traits(**traits: Any) None[source]#

Dynamically add trait attributes to the HasTraits instance.

classmethod class_config_rst_doc() str[source]#

Generate rST documentation for this class’ config options.

Excludes traits defined on parent classes.

classmethod class_config_section(classes: Sequence[type[HasTraits]] | None = None) str[source]#

Get the config section for this class.

Parameters#

classeslist, optional

The list of other classes in the config file. Used to reduce redundant information.

classmethod class_get_help(inst: HasTraits | None = None) str[source]#

Get the help string for this class in ReST format.

If inst is given, its current trait values will be used in place of class defaults.

classmethod class_get_trait_help(trait: TraitType[Any, Any], inst: HasTraits | None = None, helptext: str | None = None) str[source]#

Get the helptext string for a single trait.

Parameters:
  • inst – If given, its current trait values will be used in place of the class default.

  • helptext – If not given, uses the help attribute of the current trait.

classmethod class_own_trait_events(name: str) dict[str, EventHandler][source]#

Get a dict of all event handlers defined on this class, not a parent.

Works like event_handlers, except for excluding traits from parents.

classmethod class_own_traits(**metadata: Any) dict[str, TraitType[Any, Any]][source]#

Get a dict of all the traitlets defined on this class, not a parent.

Works like class_traits, except for excluding traits from parents.

classmethod class_print_help(inst: HasTraits | None = None) None[source]#

Get the help string for a single trait and print it.

classmethod class_trait_names(**metadata: Any) list[str][source]#

Get a list of all the names of this class’ traits.

This method is just like the trait_names() method, but is unbound.

classmethod class_traits(**metadata: Any) dict[str, TraitType[Any, Any]][source]#

Get a dict of all the traits of this class. The dictionary is keyed on the name and the values are the TraitType objects.

This method is just like the traits() method, but is unbound.

The TraitTypes returned don’t know anything about the values that the various HasTrait’s instances are holding.

The metadata kwargs allow functions to be passed in which filter traits based on metadata values. The functions should take a single value as an argument and return a boolean. If any function returns False, then the trait is not included in the output. If a metadata key doesn’t exist, None will be passed to the function.

property cross_validation_lock: Any#

A contextmanager for running a block with our cross validation lock set to True.

At the end of the block, the lock’s value is restored to its value prior to entering the block.

default_language#

Deprecated default highlight language as of 5.0, please use language_info metadata instead

display_data_priority#

An ordered list of preferred output type, the first encountered will usually be used when converting discarding the others.

has_trait(name: str) bool[source]#

Returns True if the object has a trait with the specified name.

hold_trait_notifications() Any[source]#

Context manager for bundling trait change notifications and cross validation.

Use this when doing multiple trait assignments (init, config), to avoid race conditions in trait notifiers requesting other trait values. All trait notifications will fire after all values have been assigned.

log#

Logger or LoggerAdapter instance

notify_change(change: Bunch) None[source]#

Notify observers of a change event

observe(handler: Callable[[...], Any], names: Sentinel | str | Iterable[Sentinel | str] = traitlets.All, type: Sentinel | str = 'change') None[source]#

Setup a handler to be called when a trait changes.

This is used to setup dynamic notifications of trait changes.

Parameters#

handlercallable

A callable that is called when a trait changes. Its signature should be handler(change), where change is a dictionary. The change dictionary at least holds a ‘type’ key. * type: the type of notification. Other keys may be passed depending on the value of ‘type’. In the case where type is ‘change’, we also have the following keys: * owner : the HasTraits instance * old : the old value of the modified trait attribute * new : the new value of the modified trait attribute * name : the name of the modified trait attribute.

nameslist, str, All

If names is All, the handler will apply to all traits. If a list of str, handler will apply to all names in the list. If a str, the handler will apply just to that name.

typestr, All (default: ‘change’)

The type of notification to filter by. If equal to All, then all notifications are passed to the observe handler.

on_trait_change(handler: EventHandler | None = None, name: Sentinel | str | None = None, remove: bool = False) None[source]#

DEPRECATED: Setup a handler to be called when a trait changes.

This is used to setup dynamic notifications of trait changes.

Static handlers can be created by creating methods on a HasTraits subclass with the naming convention ‘_[traitname]_changed’. Thus, to create static handler for the trait ‘a’, create the method _a_changed(self, name, old, new) (fewer arguments can be used, see below).

If remove is True and handler is not specified, all change handlers for the specified name are uninstalled.

Parameters#

handlercallable, None

A callable that is called when a trait changes. Its signature can be handler(), handler(name), handler(name, new), handler(name, old, new), or handler(name, old, new, self).

namelist, str, None

If None, the handler will apply to all traits. If a list of str, handler will apply to all names in the list. If a str, the handler will apply just to that name.

removebool

If False (the default), then install the handler. If True then unintall it.

preprocess(nb, resources)[source]#

Preprocessing to apply on each notebook.

Must return modified nb, resources.

If you wish to apply your preprocessing to each cell, you might want to override preprocess_cell method instead.

Parameters#

nbNotebookNode

Notebook being converted

resourcesdictionary

Additional resources used in the conversion process. Allows preprocessors to pass variables into the Jinja engine.

preprocess_cell(cell, resources, index)[source]#

Override if you want to apply some preprocessing to each cell. Must return modified cell and resource dictionary.

Parameters#

cellNotebookNode cell

Notebook cell being processed

resourcesdictionary

Additional resources used in the conversion process. Allows preprocessors to pass variables into the Jinja engine.

indexint

Index of the cell being processed

replace(src)[source]#

Given some source html substitute and annotated as applicable

classmethod section_names() list[str][source]#

return section names as a list

set_trait(name: str, value: Any) None[source]#

Forcibly sets trait attribute, including read-only attributes.

setup_instance(**kwargs: Any) None[source]#

This is called before self.__init__ is called.

trait_defaults(*names: str, **metadata: Any) dict[str, Any] | Sentinel[source]#

Return a trait’s default value or a dictionary of them

Notes#

Dynamically generated default values may depend on the current state of the object.

classmethod trait_events(name: str | None = None) dict[str, EventHandler][source]#

Get a dict of all the event handlers of this class.

Parameters#

namestr (default: None)

The name of a trait of this class. If name is None then all the event handlers of this class will be returned instead.

Returns#

The event handlers associated with a trait name, or all event handlers.

trait_has_value(name: str) bool[source]#

Returns True if the specified trait has a value.

This will return false even if getattr would return a dynamically generated default value. These default values will be recognized as existing only after they have been generated.

Example

class MyClass(HasTraits):
    i = Int()


mc = MyClass()
assert not mc.trait_has_value("i")
mc.i  # generates a default value
assert mc.trait_has_value("i")
trait_metadata(traitname: str, key: str, default: Any = None) Any[source]#

Get metadata values for trait by key.

trait_names(**metadata: Any) list[str][source]#

Get a list of all the names of this class’ traits.

trait_values(**metadata: Any) dict[str, Any][source]#

A dict of trait names and their values.

The metadata kwargs allow functions to be passed in which filter traits based on metadata values. The functions should take a single value as an argument and return a boolean. If any function returns False, then the trait is not included in the output. If a metadata key doesn’t exist, None will be passed to the function.

Returns#

A dict of trait names and their values.

Notes#

Trait values are retrieved via getattr, any exceptions raised by traits or the operations they may trigger will result in the absence of a trait value in the result dict.

traits(**metadata: Any) dict[str, TraitType[Any, Any]][source]#

Get a dict of all the traits of this class. The dictionary is keyed on the name and the values are the TraitType objects.

The TraitTypes returned don’t know anything about the values that the various HasTrait’s instances are holding.

The metadata kwargs allow functions to be passed in which filter traits based on metadata values. The functions should take a single value as an argument and return a boolean. If any function returns False, then the trait is not included in the output. If a metadata key doesn’t exist, None will be passed to the function.

unobserve(handler: Callable[[...], Any], names: Sentinel | str | Iterable[Sentinel | str] = traitlets.All, type: Sentinel | str = 'change') None[source]#

Remove a trait change handler.

This is used to unregister handlers to trait change notifications.

Parameters#

handlercallable

The callable called when a trait attribute changes.

nameslist, str, All (default: All)

The names of the traits for which the specified handler should be uninstalled. If names is All, the specified handler is uninstalled from the list of notifiers corresponding to all changes.

typestr or All (default: ‘change’)

The type of notification to filter by. If All, the specified handler is uninstalled from the list of notifiers corresponding to all types.

unobserve_all(name: str | Any = traitlets.All) None[source]#

Remove trait change handlers of any type for the specified name. If name is not specified, removes all trait notifiers.

update_config(config: Config) None[source]#

Update config and load the new values

holoviews.ipython.preprocessors.comment_out_magics(source)[source]#

Utility used to make sure AST parser does not choke on unrecognized magics.

holoviews.ipython.preprocessors.filter_magic(source, magic, strip=True)[source]#

Given the source of a cell, filter out the given magic and collect the lines using the magic into a list.

If strip is True, the IPython syntax part of the magic (e.g. %magic or %%magic) is stripped from the returned lines.

holoviews.ipython.preprocessors.replace_line_magic(source, magic, template='{line}')[source]#

Given a cell’s source, replace line magics using a formatting template, where {line} is the string that follows the magic.

holoviews.ipython.preprocessors.strip_magics(source)[source]#

Given the source of a cell, filter out all cell and line magics.

holoviews.ipython.preprocessors.wrap_cell_expression(source, template='{expr}')[source]#

If a cell ends in an expression that could be displaying a HoloViews object (as determined using the AST), wrap it with a given prefix and suffix string.

If the cell doesn’t end in an expression, return the source unchanged.


widgets Module#

class holoviews.ipython.widgets.ProgressBar(*, blank_char, display, elapsed_time, fill_char, width, label, percent_range, name)[source]#

Bases: ProgressIndicator

A simple text progress bar suitable for both the IPython notebook and the IPython interactive prompt.

ProgressBars are automatically nested if a previous instantiated progress bars has not achieved 100% completion.

Parameters inherited from:

display = param.ObjectSelector(allow_refs=False, default=’stdout’, label=’Display’, names={}, nested_refs=False, objects=[‘stdout’, ‘disabled’, ‘broadcast’], rx=<param.reactive.reactive_ops object at 0x162a4e6d0>)

Parameter to control display of the progress bar. By default, progress is shown on stdout but this may be disabled e.g. for jobs that log standard output to file. If the output mode is set to ‘broadcast’, a socket is opened on a stated port to broadcast the completion percentage. The RemoteProgress class may then be used to view the progress from a different process.

width = param.Integer(allow_refs=False, default=70, inclusive_bounds=(True, True), label=’Width’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x162a1b290>)

The width of the progress bar as the number of characters

fill_char = param.String(allow_refs=False, default=’#’, label=’Fill char’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x162a4de50>)

The character used to fill the progress bar.

blank_char = param.String(allow_refs=False, default=’ ‘, label=’Blank char’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x162a4f150>)

The character for the blank portion of the progress bar.

elapsed_time = param.Boolean(allow_refs=False, default=True, label=’Elapsed time’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x162a4df90>)

If enabled, the progress bar will disappear and display the total elapsed time once 100% completion is reached.

class holoviews.ipython.widgets.RemoteProgress(port, **params)[source]#

Bases: ProgressBar

Connect to a progress bar in a separate process with output_mode set to ‘broadcast’ in order to display the results (to stdout).

Parameters inherited from:

holoviews.core.util.ProgressIndicator: percent_range, label

holoviews.ipython.widgets.ProgressBar: display, width, fill_char, blank_char, elapsed_time

hostname = param.String(allow_refs=False, default=’localhost’, label=’Hostname’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x162a28790>)

Hostname where progress is being broadcast.

port = param.Integer(allow_refs=False, default=8080, inclusive_bounds=(True, True), label=’Port’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x162a443d0>)

Target port on hostname.

class holoviews.ipython.widgets.RunProgress(*, interval, run_hook, blank_char, display, elapsed_time, fill_char, width, label, percent_range, name)[source]#

Bases: ProgressBar

RunProgress breaks up the execution of a slow running command so that the level of completion can be displayed during execution.

This class is designed to run commands that take a single numeric argument that acts additively. Namely, it is expected that a slow running command ‘run_hook(X+Y)’ can be arbitrarily broken up into multiple, faster executing calls ‘run_hook(X)’ and ‘run_hook(Y)’ without affecting the overall result.

For instance, this is suitable for simulations where the numeric argument is the simulated time - typically, advancing 10 simulated seconds takes about twice as long as advancing by 5 seconds.

Parameters inherited from:

holoviews.core.util.ProgressIndicator: percent_range, label

holoviews.ipython.widgets.ProgressBar: display, width, fill_char, blank_char, elapsed_time

interval = param.Number(allow_refs=False, default=100, inclusive_bounds=(True, True), label=’Interval’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x162a602d0>)

The run interval used to break up updates to the progress bar.

run_hook = param.Callable(allow_refs=False, label=’Run hook’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x162a61750>)

By default updates time in param which is very fast and does not need a progress bar. Should be set to some slower running callable where display of progress level is desired.

holoviews.ipython.widgets.progress(iterator, enum=False, length=None)[source]#

A helper utility to display a progress bar when iterating over a collection of a fixed length or a generator (with a declared length).

If enum=True, then equivalent to enumerate with a progress bar.