index
int64 0
731k
| package
stringlengths 2
98
⌀ | name
stringlengths 1
76
| docstring
stringlengths 0
281k
⌀ | code
stringlengths 4
1.07M
⌀ | signature
stringlengths 2
42.8k
⌀ |
---|---|---|---|---|---|
14,213 | ipyleaflet.leaflet | MarkerCluster | MarkerCluster class, with Layer as parent class.
A cluster of markers that you can put on the map like other layers.
Attributes
----------
markers: list, default []
List of markers to include in the cluster.
show_coverage_on_hover: bool, default True
Mouse over a cluster to show the bounds of its markers.
zoom_to_bounds_on_click: bool, default True
Click a cluster to zoom in to its bounds.
spiderfy_on_max_zoom: bool, default True
When you click a cluster at the bottom zoom level, spiderfy it so you can see all of its markers. (Note: the spiderfy occurs at the current zoom level if all items within the cluster are still clustered at the maximum zoom level or at zoom specified by ``disableClusteringAtZoom`` option)
remove_outside_visible_bounds: bool, default True
Clusters and markers too far from the viewport are removed from the map for performance.
animate: bool, default True
Smoothly split / merge cluster children when zooming and spiderfying. If L.DomUtil.TRANSITION is false, this option has no effect (no animation is possible).
animate_adding_markers: bool, default False
If set to true (and animate option is also true) then adding individual markers to the MarkerClusterGroup after it has been added to the map will add the marker and animate it into the cluster. Defaults to false as this gives better performance when bulk adding markers.
disable_clustering_at_zoom: int, default 18
Markers will not be clustered at or below this zoom level. Note: you may be interested in disabling ``spiderfyOnMaxZoom`` option when using ``disableClusteringAtZoom``.
max_cluster_radius: int, default 80
The maximum radius that a cluster will cover from the central marker (in pixels). Decreasing will make more, smaller clusters.
polygon_options: dict, default {}
Options to pass when creating the L.Polygon(points, options) to show the bounds of a cluster. Defaults to empty, which lets Leaflet use the default `Path options <https://leafletjs.com/reference.html#path>`_.
spider_leg_polyline_options: dict, default {"weight": 1.5, "color": "#222", "opacity": 0.5}
Allows you to specify `PolylineOptions <https://leafletjs.com/reference.html#polyline>`_ to style spider legs.
spiderfy_distance_multiplier: int, default 1
Scale the distance away from the center that spiderfied markers are placed. Use if you are using big marker icons.
| class MarkerCluster(Layer):
"""MarkerCluster class, with Layer as parent class.
A cluster of markers that you can put on the map like other layers.
Attributes
----------
markers: list, default []
List of markers to include in the cluster.
show_coverage_on_hover: bool, default True
Mouse over a cluster to show the bounds of its markers.
zoom_to_bounds_on_click: bool, default True
Click a cluster to zoom in to its bounds.
spiderfy_on_max_zoom: bool, default True
When you click a cluster at the bottom zoom level, spiderfy it so you can see all of its markers. (Note: the spiderfy occurs at the current zoom level if all items within the cluster are still clustered at the maximum zoom level or at zoom specified by ``disableClusteringAtZoom`` option)
remove_outside_visible_bounds: bool, default True
Clusters and markers too far from the viewport are removed from the map for performance.
animate: bool, default True
Smoothly split / merge cluster children when zooming and spiderfying. If L.DomUtil.TRANSITION is false, this option has no effect (no animation is possible).
animate_adding_markers: bool, default False
If set to true (and animate option is also true) then adding individual markers to the MarkerClusterGroup after it has been added to the map will add the marker and animate it into the cluster. Defaults to false as this gives better performance when bulk adding markers.
disable_clustering_at_zoom: int, default 18
Markers will not be clustered at or below this zoom level. Note: you may be interested in disabling ``spiderfyOnMaxZoom`` option when using ``disableClusteringAtZoom``.
max_cluster_radius: int, default 80
The maximum radius that a cluster will cover from the central marker (in pixels). Decreasing will make more, smaller clusters.
polygon_options: dict, default {}
Options to pass when creating the L.Polygon(points, options) to show the bounds of a cluster. Defaults to empty, which lets Leaflet use the default `Path options <https://leafletjs.com/reference.html#path>`_.
spider_leg_polyline_options: dict, default {"weight": 1.5, "color": "#222", "opacity": 0.5}
Allows you to specify `PolylineOptions <https://leafletjs.com/reference.html#polyline>`_ to style spider legs.
spiderfy_distance_multiplier: int, default 1
Scale the distance away from the center that spiderfied markers are placed. Use if you are using big marker icons.
"""
_view_name = Unicode("LeafletMarkerClusterView").tag(sync=True)
_model_name = Unicode("LeafletMarkerClusterModel").tag(sync=True)
markers = Tuple().tag(trait=Instance(Layer), sync=True, **widget_serialization)
# Options
show_coverage_on_hover = Bool(True).tag(sync=True, o=True)
zoom_to_bounds_on_click = Bool(True).tag(sync=True, o=True)
spiderfy_on_max_zoom = Bool(True).tag(sync=True, o=True)
remove_outside_visible_bounds = Bool(True).tag(sync=True, o=True)
animate = Bool(True).tag(sync=True, o=True)
animate_adding_markers = Bool(False).tag(sync=True, o=True)
disable_clustering_at_zoom = Int(18).tag(sync=True, o=True)
max_cluster_radius = Int(80).tag(sync=True, o=True)
polygon_options = Dict({}).tag(sync=True, o=True)
spider_leg_polyline_options = Dict({"weight": 1.5, "color": "#222", "opacity": 0.5}).tag(sync=True, o=True)
spiderfy_distance_multiplier = Int(1).tag(sync=True, o=True)
| (*args: 't.Any', **kwargs: 't.Any') -> 't.Any' |
14,278 | ipyleaflet.leaflet | MeasureControl | MeasureControl class, with Control as parent class.
A control which allows making measurements on the Map.
Attributes
----------------------
primary_length_unit: str, default 'feet'
Possible values are 'feet', 'meters', 'miles', 'kilometers' or any user defined unit.
secondary_length_unit: str, default None
Possible values are 'feet', 'meters', 'miles', 'kilometers' or any user defined unit.
primary_area_unit: str, default 'acres'
Possible values are 'acres', 'hectares', 'sqfeet', 'sqmeters', 'sqmiles' or any user defined unit.
secondary_area_unit: str, default None
Possible values are 'acres', 'hectares', 'sqfeet', 'sqmeters', 'sqmiles' or any user defined unit.
active_color: CSS Color, default '#ABE67E'
The color used for current measurements.
completed_color: CSS Color, default '#C8F2BE'
The color used for the completed measurements.
| class MeasureControl(Control):
"""MeasureControl class, with Control as parent class.
A control which allows making measurements on the Map.
Attributes
----------------------
primary_length_unit: str, default 'feet'
Possible values are 'feet', 'meters', 'miles', 'kilometers' or any user defined unit.
secondary_length_unit: str, default None
Possible values are 'feet', 'meters', 'miles', 'kilometers' or any user defined unit.
primary_area_unit: str, default 'acres'
Possible values are 'acres', 'hectares', 'sqfeet', 'sqmeters', 'sqmiles' or any user defined unit.
secondary_area_unit: str, default None
Possible values are 'acres', 'hectares', 'sqfeet', 'sqmeters', 'sqmiles' or any user defined unit.
active_color: CSS Color, default '#ABE67E'
The color used for current measurements.
completed_color: CSS Color, default '#C8F2BE'
The color used for the completed measurements.
"""
_view_name = Unicode("LeafletMeasureControlView").tag(sync=True)
_model_name = Unicode("LeafletMeasureControlModel").tag(sync=True)
_length_units = ["feet", "meters", "miles", "kilometers"]
_area_units = ["acres", "hectares", "sqfeet", "sqmeters", "sqmiles"]
_custom_units_dict = {}
_custom_units = Dict().tag(sync=True)
primary_length_unit = Enum(
values=_length_units,
default_value="feet",
help="""Possible values are feet, meters, miles, kilometers or any user
defined unit""",
).tag(sync=True, o=True)
secondary_length_unit = Enum(
values=_length_units,
default_value=None,
allow_none=True,
help="""Possible values are feet, meters, miles, kilometers or any user
defined unit""",
).tag(sync=True, o=True)
primary_area_unit = Enum(
values=_area_units,
default_value="acres",
help="""Possible values are acres, hectares, sqfeet, sqmeters, sqmiles
or any user defined unit""",
).tag(sync=True, o=True)
secondary_area_unit = Enum(
values=_area_units,
default_value=None,
allow_none=True,
help="""Possible values are acres, hectares, sqfeet, sqmeters, sqmiles
or any user defined unit""",
).tag(sync=True, o=True)
active_color = Color("#ABE67E").tag(sync=True, o=True)
completed_color = Color("#C8F2BE").tag(sync=True, o=True)
popup_options = Dict(
{"className": "leaflet-measure-resultpopup", "autoPanPadding": [10, 10]}
).tag(sync=True, o=True)
capture_z_index = Int(10000).tag(sync=True, o=True)
def add_length_unit(self, name, factor, decimals=0):
"""Add a custom length unit.
Parameters
----------
name: str
The name for your custom unit.
factor: float
Factor to apply when converting to this unit. Length in meters
will be multiplied by this factor.
decimals: int, default 0
Number of decimals to round results when using this unit.
"""
self._length_units.append(name)
self._add_unit(name, factor, decimals)
def add_area_unit(self, name, factor, decimals=0):
"""Add a custom area unit.
Parameters
----------
name: str
The name for your custom unit.
factor: float
Factor to apply when converting to this unit. Area in sqmeters
will be multiplied by this factor.
decimals: int, default 0
Number of decimals to round results when using this unit.
"""
self._area_units.append(name)
self._add_unit(name, factor, decimals)
def _add_unit(self, name, factor, decimals):
self._custom_units_dict[name] = {
"factor": factor,
"display": name,
"decimals": decimals,
}
self._custom_units = dict(**self._custom_units_dict)
| (*args: 't.Any', **kwargs: 't.Any') -> 't.Any' |
14,288 | ipyleaflet.leaflet | _add_unit | null | def _add_unit(self, name, factor, decimals):
self._custom_units_dict[name] = {
"factor": factor,
"display": name,
"decimals": decimals,
}
self._custom_units = dict(**self._custom_units_dict)
| (self, name, factor, decimals) |
14,308 | ipyleaflet.leaflet | add_area_unit | Add a custom area unit.
Parameters
----------
name: str
The name for your custom unit.
factor: float
Factor to apply when converting to this unit. Area in sqmeters
will be multiplied by this factor.
decimals: int, default 0
Number of decimals to round results when using this unit.
| def add_area_unit(self, name, factor, decimals=0):
"""Add a custom area unit.
Parameters
----------
name: str
The name for your custom unit.
factor: float
Factor to apply when converting to this unit. Area in sqmeters
will be multiplied by this factor.
decimals: int, default 0
Number of decimals to round results when using this unit.
"""
self._area_units.append(name)
self._add_unit(name, factor, decimals)
| (self, name, factor, decimals=0) |
14,309 | ipyleaflet.leaflet | add_length_unit | Add a custom length unit.
Parameters
----------
name: str
The name for your custom unit.
factor: float
Factor to apply when converting to this unit. Length in meters
will be multiplied by this factor.
decimals: int, default 0
Number of decimals to round results when using this unit.
| def add_length_unit(self, name, factor, decimals=0):
"""Add a custom length unit.
Parameters
----------
name: str
The name for your custom unit.
factor: float
Factor to apply when converting to this unit. Length in meters
will be multiplied by this factor.
decimals: int, default 0
Number of decimals to round results when using this unit.
"""
self._length_units.append(name)
self._add_unit(name, factor, decimals)
| (self, name, factor, decimals=0) |
14,338 | ipywidgets.widgets.widget_output | Output | Widget used as a context manager to display output.
This widget can capture and display stdout, stderr, and rich output. To use
it, create an instance of it and display it.
You can then use the widget as a context manager: any output produced while in the
context will be captured and displayed in the widget instead of the standard output
area.
You can also use the .capture() method to decorate a function or a method. Any output
produced by the function will then go to the output widget. This is useful for
debugging widget callbacks, for example.
Example::
import ipywidgets as widgets
from IPython.display import display
out = widgets.Output()
display(out)
print('prints to output area')
with out:
print('prints to output widget')
@out.capture()
def func():
print('prints to output widget')
| class Output(DOMWidget):
"""Widget used as a context manager to display output.
This widget can capture and display stdout, stderr, and rich output. To use
it, create an instance of it and display it.
You can then use the widget as a context manager: any output produced while in the
context will be captured and displayed in the widget instead of the standard output
area.
You can also use the .capture() method to decorate a function or a method. Any output
produced by the function will then go to the output widget. This is useful for
debugging widget callbacks, for example.
Example::
import ipywidgets as widgets
from IPython.display import display
out = widgets.Output()
display(out)
print('prints to output area')
with out:
print('prints to output widget')
@out.capture()
def func():
print('prints to output widget')
"""
_view_name = Unicode('OutputView').tag(sync=True)
_model_name = Unicode('OutputModel').tag(sync=True)
_view_module = Unicode('@jupyter-widgets/output').tag(sync=True)
_model_module = Unicode('@jupyter-widgets/output').tag(sync=True)
_view_module_version = Unicode(__jupyter_widgets_output_version__).tag(sync=True)
_model_module_version = Unicode(__jupyter_widgets_output_version__).tag(sync=True)
msg_id = Unicode('', help="Parent message id of messages to capture").tag(sync=True)
outputs = TypedTuple(trait=Dict(), help="The output messages synced from the frontend.").tag(sync=True)
__counter = 0
def clear_output(self, *pargs, **kwargs):
"""
Clear the content of the output widget.
Parameters
----------
wait: bool
If True, wait to clear the output until new output is
available to replace it. Default: False
"""
with self:
clear_output(*pargs, **kwargs)
# PY3: Force passing clear_output and clear_kwargs as kwargs
def capture(self, clear_output=False, *clear_args, **clear_kwargs):
"""
Decorator to capture the stdout and stderr of a function.
Parameters
----------
clear_output: bool
If True, clear the content of the output widget at every
new function call. Default: False
wait: bool
If True, wait to clear the output until new output is
available to replace it. This is only used if clear_output
is also True.
Default: False
"""
def capture_decorator(func):
@wraps(func)
def inner(*args, **kwargs):
if clear_output:
self.clear_output(*clear_args, **clear_kwargs)
with self:
return func(*args, **kwargs)
return inner
return capture_decorator
def __enter__(self):
"""Called upon entering output widget context manager."""
self._flush()
ip = get_ipython()
kernel = None
if ip and getattr(ip, "kernel", None) is not None:
kernel = ip.kernel
elif self.comm is not None and getattr(self.comm, 'kernel', None) is not None:
kernel = self.comm.kernel
if kernel:
parent = None
if hasattr(kernel, "get_parent"):
parent = kernel.get_parent()
elif hasattr(kernel, "_parent_header"):
# ipykernel < 6: kernel._parent_header is the parent *request*
parent = kernel._parent_header
if parent and parent.get("header"):
self.msg_id = parent["header"]["msg_id"]
self.__counter += 1
def __exit__(self, etype, evalue, tb):
"""Called upon exiting output widget context manager."""
kernel = None
if etype is not None:
ip = get_ipython()
if ip:
kernel = ip
ip.showtraceback((etype, evalue, tb), tb_offset=0)
elif (self.comm is not None and
getattr(self.comm, "kernel", None) is not None and
# Check if it's ipykernel
getattr(self.comm.kernel, "send_response", None) is not None):
kernel = self.comm.kernel
kernel.send_response(kernel.iopub_socket,
u'error',
{
u'traceback': ["".join(traceback.format_exception(etype, evalue, tb))],
u'evalue': repr(evalue.args),
u'ename': etype.__name__
})
self._flush()
self.__counter -= 1
if self.__counter == 0:
self.msg_id = ''
# suppress exceptions when in IPython, since they are shown above,
# otherwise let someone else handle it
return True if kernel else None
def _flush(self):
"""Flush stdout and stderr buffers."""
sys.stdout.flush()
sys.stderr.flush()
def _append_stream_output(self, text, stream_name):
"""Append a stream output."""
self.outputs += (
{'output_type': 'stream', 'name': stream_name, 'text': text},
)
def append_stdout(self, text):
"""Append text to the stdout stream."""
self._append_stream_output(text, stream_name='stdout')
def append_stderr(self, text):
"""Append text to the stderr stream."""
self._append_stream_output(text, stream_name='stderr')
def append_display_data(self, display_object):
"""Append a display object as an output.
Parameters
----------
display_object : IPython.core.display.DisplayObject
The object to display (e.g., an instance of
`IPython.display.Markdown` or `IPython.display.Image`).
"""
fmt = InteractiveShell.instance().display_formatter.format
data, metadata = fmt(display_object)
self.outputs += (
{
'output_type': 'display_data',
'data': data,
'metadata': metadata
},
)
| (*args: 't.Any', **kwargs: 't.Any') -> 't.Any' |
14,342 | ipywidgets.widgets.widget_output | __enter__ | Called upon entering output widget context manager. | def __enter__(self):
"""Called upon entering output widget context manager."""
self._flush()
ip = get_ipython()
kernel = None
if ip and getattr(ip, "kernel", None) is not None:
kernel = ip.kernel
elif self.comm is not None and getattr(self.comm, 'kernel', None) is not None:
kernel = self.comm.kernel
if kernel:
parent = None
if hasattr(kernel, "get_parent"):
parent = kernel.get_parent()
elif hasattr(kernel, "_parent_header"):
# ipykernel < 6: kernel._parent_header is the parent *request*
parent = kernel._parent_header
if parent and parent.get("header"):
self.msg_id = parent["header"]["msg_id"]
self.__counter += 1
| (self) |
14,343 | ipywidgets.widgets.widget_output | __exit__ | Called upon exiting output widget context manager. | def __exit__(self, etype, evalue, tb):
"""Called upon exiting output widget context manager."""
kernel = None
if etype is not None:
ip = get_ipython()
if ip:
kernel = ip
ip.showtraceback((etype, evalue, tb), tb_offset=0)
elif (self.comm is not None and
getattr(self.comm, "kernel", None) is not None and
# Check if it's ipykernel
getattr(self.comm.kernel, "send_response", None) is not None):
kernel = self.comm.kernel
kernel.send_response(kernel.iopub_socket,
u'error',
{
u'traceback': ["".join(traceback.format_exception(etype, evalue, tb))],
u'evalue': repr(evalue.args),
u'ename': etype.__name__
})
self._flush()
self.__counter -= 1
if self.__counter == 0:
self.msg_id = ''
# suppress exceptions when in IPython, since they are shown above,
# otherwise let someone else handle it
return True if kernel else None
| (self, etype, evalue, tb) |
14,350 | ipywidgets.widgets.widget_output | _append_stream_output | Append a stream output. | def _append_stream_output(self, text, stream_name):
"""Append a stream output."""
self.outputs += (
{'output_type': 'stream', 'name': stream_name, 'text': text},
)
| (self, text, stream_name) |
14,353 | ipywidgets.widgets.widget_output | _flush | Flush stdout and stderr buffers. | def _flush(self):
"""Flush stdout and stderr buffers."""
sys.stdout.flush()
sys.stderr.flush()
| (self) |
14,373 | ipywidgets.widgets.widget_output | append_display_data | Append a display object as an output.
Parameters
----------
display_object : IPython.core.display.DisplayObject
The object to display (e.g., an instance of
`IPython.display.Markdown` or `IPython.display.Image`).
| def append_display_data(self, display_object):
"""Append a display object as an output.
Parameters
----------
display_object : IPython.core.display.DisplayObject
The object to display (e.g., an instance of
`IPython.display.Markdown` or `IPython.display.Image`).
"""
fmt = InteractiveShell.instance().display_formatter.format
data, metadata = fmt(display_object)
self.outputs += (
{
'output_type': 'display_data',
'data': data,
'metadata': metadata
},
)
| (self, display_object) |
14,374 | ipywidgets.widgets.widget_output | append_stderr | Append text to the stderr stream. | def append_stderr(self, text):
"""Append text to the stderr stream."""
self._append_stream_output(text, stream_name='stderr')
| (self, text) |
14,375 | ipywidgets.widgets.widget_output | append_stdout | Append text to the stdout stream. | def append_stdout(self, text):
"""Append text to the stdout stream."""
self._append_stream_output(text, stream_name='stdout')
| (self, text) |
14,377 | ipywidgets.widgets.widget_output | capture |
Decorator to capture the stdout and stderr of a function.
Parameters
----------
clear_output: bool
If True, clear the content of the output widget at every
new function call. Default: False
wait: bool
If True, wait to clear the output until new output is
available to replace it. This is only used if clear_output
is also True.
Default: False
| def capture(self, clear_output=False, *clear_args, **clear_kwargs):
"""
Decorator to capture the stdout and stderr of a function.
Parameters
----------
clear_output: bool
If True, clear the content of the output widget at every
new function call. Default: False
wait: bool
If True, wait to clear the output until new output is
available to replace it. This is only used if clear_output
is also True.
Default: False
"""
def capture_decorator(func):
@wraps(func)
def inner(*args, **kwargs):
if clear_output:
self.clear_output(*clear_args, **clear_kwargs)
with self:
return func(*args, **kwargs)
return inner
return capture_decorator
| (self, clear_output=False, *clear_args, **clear_kwargs) |
14,378 | ipywidgets.widgets.widget_output | clear_output |
Clear the content of the output widget.
Parameters
----------
wait: bool
If True, wait to clear the output until new output is
available to replace it. Default: False
| def clear_output(self, *pargs, **kwargs):
"""
Clear the content of the output widget.
Parameters
----------
wait: bool
If True, wait to clear the output until new output is
available to replace it. Default: False
"""
with self:
clear_output(*pargs, **kwargs)
| (self, *pargs, **kwargs) |
14,408 | ipyleaflet.leaflet | PMTilesLayer | PMTilesLayer class, with Layer as parent class.
PMTiles layer.
Attributes
----------
url: string, default ""
Url to the PMTiles archive.
attribution: string, default ""
PMTiles archive attribution.
style: dict, default {}
CSS Styles to apply to the vector data.
| class PMTilesLayer(Layer):
"""PMTilesLayer class, with Layer as parent class.
PMTiles layer.
Attributes
----------
url: string, default ""
Url to the PMTiles archive.
attribution: string, default ""
PMTiles archive attribution.
style: dict, default {}
CSS Styles to apply to the vector data.
"""
_view_name = Unicode("LeafletPMTilesLayerView").tag(sync=True)
_model_name = Unicode("LeafletPMTilesLayerModel").tag(sync=True)
url = Unicode().tag(sync=True, o=True)
attribution = Unicode().tag(sync=True, o=True)
style = Dict().tag(sync=True, o=True)
def add_inspector(self):
"""Add an inspector to the layer."""
self.send({"msg": "add_inspector"})
| (*args: 't.Any', **kwargs: 't.Any') -> 't.Any' |
14,438 | ipyleaflet.leaflet | add_inspector | Add an inspector to the layer. | def add_inspector(self):
"""Add an inspector to the layer."""
self.send({"msg": "add_inspector"})
| (self) |
14,474 | ipyleaflet.leaflet | PaneException | Custom PaneException class. | class PaneException(TraitError):
"""Custom PaneException class."""
pass
| null |
14,475 | ipyleaflet.leaflet | Path | Path abstract class.
Path layer.
Attributes
----------
stroke: boolean, default True
Whether to draw a stroke.
color: CSS color, default '#0033FF'
CSS color.
weight: int, default 5
Weight of the stroke.
fill: boolean, default True
Whether to fill the path with a flat color.
fill_color: CSS color, default None
Color used for filling the path shape. If None, the color attribute
value is used.
fill_opacity: float, default 0.2
Opacity used for filling the path shape.
line_cap: string, default "round"
A string that defines shape to be used at the end of the stroke.
Possible values are 'round', 'butt' or 'square'.
line_join: string, default "round"
A string that defines shape to be used at the corners of the stroke.
Possible values are 'arcs', 'bevel', 'miter', 'miter-clip' or 'round'.
| class Path(VectorLayer):
"""Path abstract class.
Path layer.
Attributes
----------
stroke: boolean, default True
Whether to draw a stroke.
color: CSS color, default '#0033FF'
CSS color.
weight: int, default 5
Weight of the stroke.
fill: boolean, default True
Whether to fill the path with a flat color.
fill_color: CSS color, default None
Color used for filling the path shape. If None, the color attribute
value is used.
fill_opacity: float, default 0.2
Opacity used for filling the path shape.
line_cap: string, default "round"
A string that defines shape to be used at the end of the stroke.
Possible values are 'round', 'butt' or 'square'.
line_join: string, default "round"
A string that defines shape to be used at the corners of the stroke.
Possible values are 'arcs', 'bevel', 'miter', 'miter-clip' or 'round'.
"""
_view_name = Unicode("LeafletPathView").tag(sync=True)
_model_name = Unicode("LeafletPathModel").tag(sync=True)
# Options
stroke = Bool(True).tag(sync=True, o=True)
color = Color("#0033FF").tag(sync=True, o=True)
weight = Int(5).tag(sync=True, o=True)
fill = Bool(True).tag(sync=True, o=True)
fill_color = Color(None, allow_none=True).tag(sync=True, o=True)
fill_opacity = Float(0.2).tag(sync=True, o=True)
dash_array = Unicode(allow_none=True, default_value=None).tag(sync=True, o=True)
line_cap = Enum(values=["round", "butt", "square"], default_value="round").tag(
sync=True, o=True
)
line_join = Enum(
values=["arcs", "bevel", "miter", "miter-clip", "round"], default_value="round"
).tag(sync=True, o=True)
pointer_events = Unicode("").tag(sync=True, o=True)
opacity = Float(1.0, min=0.0, max=1.0).tag(sync=True, o=True)
| (*args: 't.Any', **kwargs: 't.Any') -> 't.Any' |
14,540 | ipyleaflet.leaflet | Polygon | Polygon class, with Polyline as parent class.
Polygon layer.
| class Polygon(Polyline):
"""Polygon class, with Polyline as parent class.
Polygon layer.
"""
_view_name = Unicode("LeafletPolygonView").tag(sync=True)
_model_name = Unicode("LeafletPolygonModel").tag(sync=True)
| (*args: 't.Any', **kwargs: 't.Any') -> 't.Any' |
14,605 | ipyleaflet.leaflet | Polyline | Polyline abstract class, with Path as parent class.
Attributes
----------
locations: list, default []
Locations defining the shape.
scaling: boolean, default True
Whether you can edit the scale of the shape or not.
rotation: boolean, default True
Whether you can rotate the shape or not.
uniform_scaling: boolean, default False
Whether to keep the size ratio when changing the shape scale.
smooth_factor: float, default 1.
Smoothing intensity.
transform: boolean, default False
Whether the shape is editable or not.
draggable: boolean, default False
Whether you can drag the shape on the map or not.
| class Polyline(Path):
"""Polyline abstract class, with Path as parent class.
Attributes
----------
locations: list, default []
Locations defining the shape.
scaling: boolean, default True
Whether you can edit the scale of the shape or not.
rotation: boolean, default True
Whether you can rotate the shape or not.
uniform_scaling: boolean, default False
Whether to keep the size ratio when changing the shape scale.
smooth_factor: float, default 1.
Smoothing intensity.
transform: boolean, default False
Whether the shape is editable or not.
draggable: boolean, default False
Whether you can drag the shape on the map or not.
"""
_view_name = Unicode("LeafletPolylineView").tag(sync=True)
_model_name = Unicode("LeafletPolylineModel").tag(sync=True)
locations = List().tag(sync=True)
scaling = Bool(True).tag(sync=True)
rotation = Bool(True).tag(sync=True)
uniform_scaling = Bool(False).tag(sync=True)
# Options
smooth_factor = Float(1.0).tag(sync=True, o=True)
no_clip = Bool(True).tag(sync=True, o=True)
transform = Bool(False).tag(sync=True, o=True)
draggable = Bool(False).tag(sync=True, o=True)
| (*args: 't.Any', **kwargs: 't.Any') -> 't.Any' |
14,670 | ipyleaflet.leaflet | Popup | Popup class.
Popup element that can be placed on the map.
Attributes
----------
location: tuple, default (0, 0)
The tuple containing the latitude/longitude of the popup.
child: object, default None
Child widget that the Popup will contain.
min_width: int, default 50
Minimum width of the Popup.
max_width: int, default 300
Maximum width of the Popup.
max_height: int, default None
Maximum height of the Popup.
auto_pan: boolean, default True
Set it to False if you don’t want the map to do panning
animation to fit the opened popup.
auto_pan_padding: tuple, default (5, 5)
keep_in_view: boolean, default False
Set it to True if you want to prevent users from panning
the popup off of the screen while it is open.
close_button: boolean, default True
Whether to show a close button or not.
auto_close: boolean, default True
Whether to automatically close the popup when interacting
with another element of the map or not.
close_on_escape_key: boolean, default True
Whether to close the popup when clicking the escape key or not.
| class Popup(UILayer):
"""Popup class.
Popup element that can be placed on the map.
Attributes
----------
location: tuple, default (0, 0)
The tuple containing the latitude/longitude of the popup.
child: object, default None
Child widget that the Popup will contain.
min_width: int, default 50
Minimum width of the Popup.
max_width: int, default 300
Maximum width of the Popup.
max_height: int, default None
Maximum height of the Popup.
auto_pan: boolean, default True
Set it to False if you don’t want the map to do panning
animation to fit the opened popup.
auto_pan_padding: tuple, default (5, 5)
keep_in_view: boolean, default False
Set it to True if you want to prevent users from panning
the popup off of the screen while it is open.
close_button: boolean, default True
Whether to show a close button or not.
auto_close: boolean, default True
Whether to automatically close the popup when interacting
with another element of the map or not.
close_on_escape_key: boolean, default True
Whether to close the popup when clicking the escape key or not.
"""
_view_name = Unicode("LeafletPopupView").tag(sync=True)
_model_name = Unicode("LeafletPopupModel").tag(sync=True)
location = List(def_loc).tag(sync=True)
child = Instance(DOMWidget, allow_none=True, default_value=None).tag(
sync=True, **widget_serialization
)
# Options
min_width = Int(50).tag(sync=True, o=True)
max_width = Int(300).tag(sync=True, o=True)
max_height = Int(default_value=None, allow_none=True).tag(sync=True, o=True)
auto_pan = Bool(True).tag(sync=True, o=True)
auto_pan_padding_top_left = List(allow_none=True, default_value=None).tag(
sync=True, o=True
)
auto_pan_padding_bottom_right = List(allow_none=True, default_value=None).tag(
sync=True, o=True
)
auto_pan_padding = List([5, 5]).tag(sync=True, o=True)
keep_in_view = Bool(False).tag(sync=True, o=True)
close_button = Bool(True).tag(sync=True, o=True)
auto_close = Bool(True).tag(sync=True, o=True)
close_on_escape_key = Bool(True).tag(sync=True, o=True)
def open_popup(self, location=None):
"""Open the popup on the bound map.
Parameters
----------
location: list, default to the internal location
The location to open the popup at.
"""
if location is not None:
self.location = location
self.send(
{"msg": "open", "location": self.location if location is None else location}
)
def close_popup(self):
"""Close the popup on the bound map."""
self.send({"msg": "close"})
| (*args: 't.Any', **kwargs: 't.Any') -> 't.Any' |
14,702 | ipyleaflet.leaflet | close_popup | Close the popup on the bound map. | def close_popup(self):
"""Close the popup on the bound map."""
self.send({"msg": "close"})
| (self) |
14,723 | ipyleaflet.leaflet | open_popup | Open the popup on the bound map.
Parameters
----------
location: list, default to the internal location
The location to open the popup at.
| def open_popup(self, location=None):
"""Open the popup on the bound map.
Parameters
----------
location: list, default to the internal location
The location to open the popup at.
"""
if location is not None:
self.location = location
self.send(
{"msg": "open", "location": self.location if location is None else location}
)
| (self, location=None) |
14,737 | ipyleaflet.leaflet | RasterLayer | Abstract RasterLayer class.
Attributes
----------
opacity: float, default 1.
Opacity of the layer between 0. (fully transparent) and 1. (fully opaque).
visible: boolean, default True
Whether the layer is visible or not.
| class RasterLayer(Layer):
"""Abstract RasterLayer class.
Attributes
----------
opacity: float, default 1.
Opacity of the layer between 0. (fully transparent) and 1. (fully opaque).
visible: boolean, default True
Whether the layer is visible or not.
"""
_view_name = Unicode("LeafletRasterLayerView").tag(sync=True)
_model_name = Unicode("LeafletRasterLayerModel").tag(sync=True)
opacity = Float(1.0, min=0.0, max=1.0).tag(sync=True)
visible = Bool(True).tag(sync=True)
| (*args: 't.Any', **kwargs: 't.Any') -> 't.Any' |
14,802 | ipyleaflet.leaflet | Rectangle | Rectangle class, with Polygon as parent class.
Rectangle layer.
Attributes
----------
bounds: list, default []
List of SW and NE location tuples. e.g. [(50, 75), (75, 120)].
| class Rectangle(Polygon):
"""Rectangle class, with Polygon as parent class.
Rectangle layer.
Attributes
----------
bounds: list, default []
List of SW and NE location tuples. e.g. [(50, 75), (75, 120)].
"""
_view_name = Unicode("LeafletRectangleView").tag(sync=True)
_model_name = Unicode("LeafletRectangleModel").tag(sync=True)
bounds = List(help="list of SW and NE location tuples").tag(sync=True)
| (*args: 't.Any', **kwargs: 't.Any') -> 't.Any' |
14,867 | ipyleaflet.leaflet | ScaleControl | ScaleControl class, with Control as parent class.
A control which shows the Map scale.
Attributes
----------
max_width: int, default 100
Max width of the control, in pixels.
metric: bool, default True
Whether to show metric units.
imperial: bool, default True
Whether to show imperial units.
| class ScaleControl(Control):
"""ScaleControl class, with Control as parent class.
A control which shows the Map scale.
Attributes
----------
max_width: int, default 100
Max width of the control, in pixels.
metric: bool, default True
Whether to show metric units.
imperial: bool, default True
Whether to show imperial units.
"""
_view_name = Unicode("LeafletScaleControlView").tag(sync=True)
_model_name = Unicode("LeafletScaleControlModel").tag(sync=True)
max_width = Int(100).tag(sync=True, o=True)
metric = Bool(True).tag(sync=True, o=True)
imperial = Bool(True).tag(sync=True, o=True)
update_when_idle = Bool(False).tag(sync=True, o=True)
| (*args: 't.Any', **kwargs: 't.Any') -> 't.Any' |
14,924 | ipyleaflet.leaflet | SearchControl | SearchControl class, with Control as parent class.
Attributes
----------
url: string, default ""
The url used for the search queries.
layer: default None
The LayerGroup used for search queries.
zoom: int, default None
The zoom level after moving to searched location, by default zoom level will not change.
marker: default Marker()
The marker used by the control.
found_style: default {‘fillColor’: ‘#3f0’, ‘color’: ‘#0f0’}
Style for searched feature when searching in LayerGroup.
| class SearchControl(Control):
"""SearchControl class, with Control as parent class.
Attributes
----------
url: string, default ""
The url used for the search queries.
layer: default None
The LayerGroup used for search queries.
zoom: int, default None
The zoom level after moving to searched location, by default zoom level will not change.
marker: default Marker()
The marker used by the control.
found_style: default {‘fillColor’: ‘#3f0’, ‘color’: ‘#0f0’}
Style for searched feature when searching in LayerGroup.
"""
_view_name = Unicode("LeafletSearchControlView").tag(sync=True)
_model_name = Unicode("LeafletSearchControlModel").tag(sync=True)
url = Unicode().tag(sync=True, o=True)
zoom = Int(default_value=None, allow_none=True).tag(sync=True, o=True)
property_name = Unicode("display_name").tag(sync=True, o=True)
property_loc = List(["lat", "lon"]).tag(sync=True, o=True)
jsonp_param = Unicode("json_callback").tag(sync=True, o=True)
auto_type = Bool(False).tag(sync=True, o=True)
auto_collapse = Bool(False).tag(sync=True, o=True)
animate_location = Bool(False).tag(sync=True, o=True)
found_style = Dict(default_value={"fillColor": "#3f0", "color": "#0f0"}).tag(
sync=True, o=True
)
marker = Instance(Marker, allow_none=True, default_value=None).tag(
sync=True, **widget_serialization
)
layer = Instance(LayerGroup, allow_none=True, default_value=None).tag(
sync=True, **widget_serialization
)
_location_found_callbacks = Instance(CallbackDispatcher, ())
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.on_msg(self._handle_leaflet_event)
def _handle_leaflet_event(self, _, content, buffers):
if content.get("event", "") == "locationfound":
self._location_found_callbacks(**content)
def on_feature_found(self, callback, remove=False):
"""Add a found feature event listener for searching in GeoJSON layer.
Parameters
----------
callback : callable
Callback function that will be called on found event when searching in GeoJSON layer.
remove: boolean
Whether to remove this callback or not. Defaults to False.
"""
self._location_found_callbacks.register_callback(callback, remove=remove)
def on_location_found(self, callback, remove=False):
"""Add a found location event listener. The callback will be called when a search result has been found.
Parameters
----------
callback : callable
Callback function that will be called on location found event.
remove: boolean
Whether to remove this callback or not. Defaults to False.
"""
self._location_found_callbacks.register_callback(callback, remove=remove)
| (**kwargs) |
14,929 | ipyleaflet.leaflet | __init__ | null | def __init__(self, **kwargs):
super().__init__(**kwargs)
self.on_msg(self._handle_leaflet_event)
| (self, **kwargs) |
14,940 | ipyleaflet.leaflet | _handle_leaflet_event | null | def _handle_leaflet_event(self, _, content, buffers):
if content.get("event", "") == "locationfound":
self._location_found_callbacks(**content)
| (self, _, content, buffers) |
14,965 | ipyleaflet.leaflet | on_feature_found | Add a found feature event listener for searching in GeoJSON layer.
Parameters
----------
callback : callable
Callback function that will be called on found event when searching in GeoJSON layer.
remove: boolean
Whether to remove this callback or not. Defaults to False.
| def on_feature_found(self, callback, remove=False):
"""Add a found feature event listener for searching in GeoJSON layer.
Parameters
----------
callback : callable
Callback function that will be called on found event when searching in GeoJSON layer.
remove: boolean
Whether to remove this callback or not. Defaults to False.
"""
self._location_found_callbacks.register_callback(callback, remove=remove)
| (self, callback, remove=False) |
14,966 | ipyleaflet.leaflet | on_location_found | Add a found location event listener. The callback will be called when a search result has been found.
Parameters
----------
callback : callable
Callback function that will be called on location found event.
remove: boolean
Whether to remove this callback or not. Defaults to False.
| def on_location_found(self, callback, remove=False):
"""Add a found location event listener. The callback will be called when a search result has been found.
Parameters
----------
callback : callable
Callback function that will be called on location found event.
remove: boolean
Whether to remove this callback or not. Defaults to False.
"""
self._location_found_callbacks.register_callback(callback, remove=remove)
| (self, callback, remove=False) |
14,984 | ipyleaflet.leaflet | SplitMapControl | SplitMapControl class, with Control as parent class.
A control which allows comparing layers by splitting the map in two.
Attributes
----------
left_layer: Layer or list of Layers
The left layer(s) for comparison.
right_layer: Layer or list of Layers
The right layer(s) for comparison.
| class SplitMapControl(Control):
"""SplitMapControl class, with Control as parent class.
A control which allows comparing layers by splitting the map in two.
Attributes
----------
left_layer: Layer or list of Layers
The left layer(s) for comparison.
right_layer: Layer or list of Layers
The right layer(s) for comparison.
"""
_view_name = Unicode("LeafletSplitMapControlView").tag(sync=True)
_model_name = Unicode("LeafletSplitMapControlModel").tag(sync=True)
left_layer = Union((Instance(Layer), List(Instance(Layer)))).tag(
sync=True, **widget_serialization
)
right_layer = Union((Instance(Layer), List(Instance(Layer)))).tag(
sync=True, **widget_serialization
)
@default("left_layer")
def _default_left_layer(self):
# TODO: Shouldn't this be None?
return TileLayer()
@default("right_layer")
def _default_right_layer(self):
# TODO: Shouldn't this be None?
return TileLayer()
def __init__(self, **kwargs):
super(SplitMapControl, self).__init__(**kwargs)
self.on_msg(self._handle_leaflet_event)
def _handle_leaflet_event(self, _, content, buffers):
if content.get("event", "") == "dividermove":
event = content.get("event")
# TODO: Add x trait?
self.x = event.x
| (**kwargs) |
14,989 | ipyleaflet.leaflet | __init__ | null | def __init__(self, **kwargs):
super(SplitMapControl, self).__init__(**kwargs)
self.on_msg(self._handle_leaflet_event)
| (self, **kwargs) |
15,000 | ipyleaflet.leaflet | _handle_leaflet_event | null | def _handle_leaflet_event(self, _, content, buffers):
if content.get("event", "") == "dividermove":
event = content.get("event")
# TODO: Add x trait?
self.x = event.x
| (self, _, content, buffers) |
15,042 | ipywidgets.widgets.widget_style | Style | Style specification | class Style(Widget):
"""Style specification"""
_model_name = Unicode('StyleModel').tag(sync=True)
_view_name = Unicode('StyleView').tag(sync=True)
_view_module = Unicode('@jupyter-widgets/base').tag(sync=True)
_view_module_version = Unicode(__jupyter_widgets_base_version__).tag(sync=True)
| (*args: 't.Any', **kwargs: 't.Any') -> 't.Any' |
15,099 | ipyleaflet.leaflet | TileLayer | TileLayer class.
Tile service layer.
Attributes
----------
url: string, default "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
Url to the tiles service.
min_zoom: int, default 0
The minimum zoom level down to which this layer will be displayed (inclusive).
max_zoom: int, default 18
The maximum zoom level up to which this layer will be displayed (inclusive).
min_native_zoom: int, default None
Minimum zoom number the tile source has available. If it is specified, the tiles on all zoom levels lower than min_native_zoom will be loaded from min_native_zoom level and auto-scaled.
max_native_zoom: int, default None
Maximum zoom number the tile source has available. If it is specified, the tiles on all zoom levels higher than max_native_zoom will be loaded from max_native_zoom level and auto-scaled.
bounds: list or None, default None
List of SW and NE location tuples. e.g. [(50, 75), (75, 120)].
tile_size: int, default 256
Tile sizes for this tile service.
attribution: string, default None.
Tiles service attribution.
no_wrap: boolean, default False
Whether the layer is wrapped around the antimeridian.
tms: boolean, default False
If true, inverses Y axis numbering for tiles (turn this on for TMS services).
zoom_offset: int, default 0
The zoom number used in tile URLs will be offset with this value.
show_loading: boolean, default False
Whether to show a spinner when tiles are loading.
loading: boolean, default False (dynamically updated)
Whether the tiles are currently loading.
detect_retina: boolean, default False
opacity: float, default 1.0
visible: boolean, default True
| class TileLayer(RasterLayer):
"""TileLayer class.
Tile service layer.
Attributes
----------
url: string, default "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
Url to the tiles service.
min_zoom: int, default 0
The minimum zoom level down to which this layer will be displayed (inclusive).
max_zoom: int, default 18
The maximum zoom level up to which this layer will be displayed (inclusive).
min_native_zoom: int, default None
Minimum zoom number the tile source has available. If it is specified, the tiles on all zoom levels lower than min_native_zoom will be loaded from min_native_zoom level and auto-scaled.
max_native_zoom: int, default None
Maximum zoom number the tile source has available. If it is specified, the tiles on all zoom levels higher than max_native_zoom will be loaded from max_native_zoom level and auto-scaled.
bounds: list or None, default None
List of SW and NE location tuples. e.g. [(50, 75), (75, 120)].
tile_size: int, default 256
Tile sizes for this tile service.
attribution: string, default None.
Tiles service attribution.
no_wrap: boolean, default False
Whether the layer is wrapped around the antimeridian.
tms: boolean, default False
If true, inverses Y axis numbering for tiles (turn this on for TMS services).
zoom_offset: int, default 0
The zoom number used in tile URLs will be offset with this value.
show_loading: boolean, default False
Whether to show a spinner when tiles are loading.
loading: boolean, default False (dynamically updated)
Whether the tiles are currently loading.
detect_retina: boolean, default False
opacity: float, default 1.0
visible: boolean, default True
"""
_view_name = Unicode("LeafletTileLayerView").tag(sync=True)
_model_name = Unicode("LeafletTileLayerModel").tag(sync=True)
bottom = Bool(True).tag(sync=True)
url = Unicode("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png").tag(sync=True)
min_zoom = Int(0).tag(sync=True, o=True)
max_zoom = Int(18).tag(sync=True, o=True)
min_native_zoom = Int(default_value=None, allow_none=True).tag(sync=True, o=True)
max_native_zoom = Int(default_value=None, allow_none=True).tag(sync=True, o=True)
bounds = List(
default_value=None, allow_none=True, help="list of SW and NE location tuples"
).tag(sync=True, o=True)
tile_size = Int(256).tag(sync=True, o=True)
attribution = Unicode(default_value=None, allow_none=True).tag(sync=True, o=True)
detect_retina = Bool(False).tag(sync=True, o=True)
no_wrap = Bool(False).tag(sync=True, o=True)
tms = Bool(False).tag(sync=True, o=True)
zoom_offset = Int(0).tag(sync=True, o=True)
show_loading = Bool(False).tag(sync=True)
loading = Bool(False, read_only=True).tag(sync=True)
_load_callbacks = Instance(CallbackDispatcher, ())
def __init__(self, **kwargs):
super(TileLayer, self).__init__(**kwargs)
self.on_msg(self._handle_leaflet_event)
def _handle_leaflet_event(self, _, content, buffers):
if content.get("event", "") == "load":
self._load_callbacks(**content)
def on_load(self, callback, remove=False):
"""Add a load event listener.
Parameters
----------
callback : callable
Callback function that will be called when the tiles have finished loading.
remove: boolean
Whether to remove this callback or not. Defaults to False.
"""
self._load_callbacks.register_callback(callback, remove=remove)
def redraw(self):
"""Force redrawing the tiles.
This is especially useful when you are sure the server updated the tiles and you
need to refresh the layer.
"""
self.send({"msg": "redraw"})
| (**kwargs) |
15,167 | traitlets.traitlets | TraitError | null | class TraitError(Exception):
pass
| null |
15,168 | traitlets.traitlets | Tuple | An instance of a Python tuple. | class Tuple(Container[t.Tuple[t.Any, ...]]):
"""An instance of a Python tuple."""
klass = tuple
_cast_types = (list,)
def __init__(self, *traits: t.Any, **kwargs: t.Any) -> None:
"""Create a tuple from a list, set, or tuple.
Create a fixed-type tuple with Traits:
``t = Tuple(Int(), Str(), CStr())``
would be length 3, with Int,Str,CStr for each element.
If only one arg is given and it is not a Trait, it is taken as
default_value:
``t = Tuple((1, 2, 3))``
Otherwise, ``default_value`` *must* be specified by keyword.
Parameters
----------
*traits : TraitTypes [ optional ]
the types for restricting the contents of the Tuple. If unspecified,
types are not checked. If specified, then each positional argument
corresponds to an element of the tuple. Tuples defined with traits
are of fixed length.
default_value : SequenceType [ optional ]
The default value for the Tuple. Must be list/tuple/set, and
will be cast to a tuple. If ``traits`` are specified,
``default_value`` must conform to the shape and type they specify.
**kwargs
Other kwargs passed to `Container`
"""
default_value = kwargs.pop("default_value", Undefined)
# allow Tuple((values,)):
if len(traits) == 1 and default_value is Undefined and not is_trait(traits[0]):
default_value = traits[0]
traits = ()
if default_value is None and not kwargs.get("allow_none", False):
# improve backward-compatibility for possible subclasses
# specifying default_value=None as default,
# keeping 'unspecified' behavior (i.e. empty container)
warn(
f"Specifying {self.__class__.__name__}(default_value=None)"
" for no default is deprecated in traitlets 5.0.5."
" Use default_value=Undefined",
DeprecationWarning,
stacklevel=2,
)
default_value = Undefined
if default_value is Undefined:
args: t.Any = ()
elif default_value is None:
# default_value back on kwargs for super() to handle
args = ()
kwargs["default_value"] = None
elif isinstance(default_value, self._valid_defaults):
args = (default_value,)
else:
raise TypeError(f"default value of {self.__class__.__name__} was {default_value}")
self._traits = []
for trait in traits:
if isinstance(trait, type):
warn(
"Traits should be given as instances, not types (for example, `Int()`, not `Int`)"
" Passing types is deprecated in traitlets 4.1.",
DeprecationWarning,
stacklevel=2,
)
trait = trait()
self._traits.append(trait)
if self._traits and (default_value is None or default_value is Undefined):
# don't allow default to be an empty container if length is specified
args = None
super(Container, self).__init__(klass=self.klass, args=args, **kwargs)
def item_from_string(self, s: str, index: int) -> t.Any: # type:ignore[override]
"""Cast a single item from a string
Evaluated when parsing CLI configuration from a string
"""
if not self._traits or index >= len(self._traits):
# return s instead of raising index error
# length errors will be raised later on validation
return s
return self._traits[index].from_string(s)
def validate_elements(self, obj: t.Any, value: t.Any) -> t.Any:
if not self._traits:
# nothing to validate
return value
if len(value) != len(self._traits):
e = (
"The '%s' trait of %s instance requires %i elements, but a value of %s was specified."
% (self.name, class_of(obj), len(self._traits), repr_type(value))
)
raise TraitError(e)
validated = []
for trait, v in zip(self._traits, value):
try:
v = trait._validate(obj, v)
except TraitError as error:
self.error(obj, v, error)
else:
validated.append(v)
return tuple(validated)
def class_init(self, cls: type[t.Any], name: str | None) -> None:
for trait in self._traits:
if isinstance(trait, TraitType):
trait.class_init(cls, None)
super(Container, self).class_init(cls, name)
def subclass_init(self, cls: type[t.Any]) -> None:
for trait in self._traits:
if isinstance(trait, TraitType):
trait.subclass_init(cls)
# explicitly not calling super().subclass_init(cls)
# to opt out of instance_init
| (*traits: 't.Any', **kwargs: 't.Any') -> 'None' |
15,170 | traitlets.traitlets | __init__ | Create a tuple from a list, set, or tuple.
Create a fixed-type tuple with Traits:
``t = Tuple(Int(), Str(), CStr())``
would be length 3, with Int,Str,CStr for each element.
If only one arg is given and it is not a Trait, it is taken as
default_value:
``t = Tuple((1, 2, 3))``
Otherwise, ``default_value`` *must* be specified by keyword.
Parameters
----------
*traits : TraitTypes [ optional ]
the types for restricting the contents of the Tuple. If unspecified,
types are not checked. If specified, then each positional argument
corresponds to an element of the tuple. Tuples defined with traits
are of fixed length.
default_value : SequenceType [ optional ]
The default value for the Tuple. Must be list/tuple/set, and
will be cast to a tuple. If ``traits`` are specified,
``default_value`` must conform to the shape and type they specify.
**kwargs
Other kwargs passed to `Container`
| def __init__(self, *traits: t.Any, **kwargs: t.Any) -> None:
"""Create a tuple from a list, set, or tuple.
Create a fixed-type tuple with Traits:
``t = Tuple(Int(), Str(), CStr())``
would be length 3, with Int,Str,CStr for each element.
If only one arg is given and it is not a Trait, it is taken as
default_value:
``t = Tuple((1, 2, 3))``
Otherwise, ``default_value`` *must* be specified by keyword.
Parameters
----------
*traits : TraitTypes [ optional ]
the types for restricting the contents of the Tuple. If unspecified,
types are not checked. If specified, then each positional argument
corresponds to an element of the tuple. Tuples defined with traits
are of fixed length.
default_value : SequenceType [ optional ]
The default value for the Tuple. Must be list/tuple/set, and
will be cast to a tuple. If ``traits`` are specified,
``default_value`` must conform to the shape and type they specify.
**kwargs
Other kwargs passed to `Container`
"""
default_value = kwargs.pop("default_value", Undefined)
# allow Tuple((values,)):
if len(traits) == 1 and default_value is Undefined and not is_trait(traits[0]):
default_value = traits[0]
traits = ()
if default_value is None and not kwargs.get("allow_none", False):
# improve backward-compatibility for possible subclasses
# specifying default_value=None as default,
# keeping 'unspecified' behavior (i.e. empty container)
warn(
f"Specifying {self.__class__.__name__}(default_value=None)"
" for no default is deprecated in traitlets 5.0.5."
" Use default_value=Undefined",
DeprecationWarning,
stacklevel=2,
)
default_value = Undefined
if default_value is Undefined:
args: t.Any = ()
elif default_value is None:
# default_value back on kwargs for super() to handle
args = ()
kwargs["default_value"] = None
elif isinstance(default_value, self._valid_defaults):
args = (default_value,)
else:
raise TypeError(f"default value of {self.__class__.__name__} was {default_value}")
self._traits = []
for trait in traits:
if isinstance(trait, type):
warn(
"Traits should be given as instances, not types (for example, `Int()`, not `Int`)"
" Passing types is deprecated in traitlets 4.1.",
DeprecationWarning,
stacklevel=2,
)
trait = trait()
self._traits.append(trait)
if self._traits and (default_value is None or default_value is Undefined):
# don't allow default to be an empty container if length is specified
args = None
super(Container, self).__init__(klass=self.klass, args=args, **kwargs)
| (self, *traits: Any, **kwargs: Any) -> NoneType |
15,177 | traitlets.traitlets | class_init | null | def class_init(self, cls: type[t.Any], name: str | None) -> None:
for trait in self._traits:
if isinstance(trait, TraitType):
trait.class_init(cls, None)
super(Container, self).class_init(cls, name)
| (self, cls: type[typing.Any], name: str | None) -> NoneType |
15,189 | traitlets.traitlets | item_from_string | Cast a single item from a string
Evaluated when parsing CLI configuration from a string
| def item_from_string(self, s: str, index: int) -> t.Any: # type:ignore[override]
"""Cast a single item from a string
Evaluated when parsing CLI configuration from a string
"""
if not self._traits or index >= len(self._traits):
# return s instead of raising index error
# length errors will be raised later on validation
return s
return self._traits[index].from_string(s)
| (self, s: str, index: int) -> Any |
15,193 | traitlets.traitlets | subclass_init | null | def subclass_init(self, cls: type[t.Any]) -> None:
for trait in self._traits:
if isinstance(trait, TraitType):
trait.subclass_init(cls)
# explicitly not calling super().subclass_init(cls)
# to opt out of instance_init
| (self, cls: type[typing.Any]) -> NoneType |
15,196 | traitlets.traitlets | validate_elements | null | def validate_elements(self, obj: t.Any, value: t.Any) -> t.Any:
if not self._traits:
# nothing to validate
return value
if len(value) != len(self._traits):
e = (
"The '%s' trait of %s instance requires %i elements, but a value of %s was specified."
% (self.name, class_of(obj), len(self._traits), repr_type(value))
)
raise TraitError(e)
validated = []
for trait, v in zip(self._traits, value):
try:
v = trait._validate(obj, v)
except TraitError as error:
self.error(obj, v, error)
else:
validated.append(v)
return tuple(validated)
| (self, obj: Any, value: Any) -> Any |
15,197 | ipyleaflet.leaflet | UILayer | Abstract UILayer class. | class UILayer(Layer):
"""Abstract UILayer class."""
_view_name = Unicode("LeafletUILayerView").tag(sync=True)
_model_name = Unicode("LeafletUILayerModel").tag(sync=True)
| (*args: 't.Any', **kwargs: 't.Any') -> 't.Any' |
15,262 | traitlets.traitlets | Unicode | A trait for unicode strings. | class Unicode(TraitType[G, S]):
"""A trait for unicode strings."""
default_value = ""
info_text = "a unicode string"
if t.TYPE_CHECKING:
@t.overload
def __init__(
self: Unicode[str, str | bytes],
default_value: str | Sentinel = ...,
allow_none: Literal[False] = ...,
read_only: bool | None = ...,
help: str | None = ...,
config: t.Any = ...,
**kwargs: t.Any,
) -> None:
...
@t.overload
def __init__(
self: Unicode[str | None, str | bytes | None],
default_value: str | Sentinel | None = ...,
allow_none: Literal[True] = ...,
read_only: bool | None = ...,
help: str | None = ...,
config: t.Any = ...,
**kwargs: t.Any,
) -> None:
...
def __init__(
self: Unicode[str | None, str | bytes | None],
default_value: str | Sentinel | None = ...,
allow_none: bool = ...,
read_only: bool | None = ...,
help: str | None = ...,
config: t.Any = ...,
**kwargs: t.Any,
) -> None:
...
def validate(self, obj: t.Any, value: t.Any) -> G:
if isinstance(value, str):
return t.cast(G, value)
if isinstance(value, bytes):
try:
return t.cast(G, value.decode("ascii", "strict"))
except UnicodeDecodeError as e:
msg = "Could not decode {!r} for unicode trait '{}' of {} instance."
raise TraitError(msg.format(value, self.name, class_of(obj))) from e
self.error(obj, value)
def from_string(self, s: str) -> G:
if self.allow_none and s == "None":
return t.cast(G, None)
s = os.path.expanduser(s)
if len(s) >= 2:
# handle deprecated "1"
for c in ('"', "'"):
if s[0] == s[-1] == c:
old_s = s
s = s[1:-1]
warn(
"Supporting extra quotes around strings is deprecated in traitlets 5.0. "
f"You can use {s!r} instead of {old_s!r} if you require traitlets >=5.",
DeprecationWarning,
stacklevel=2,
)
return t.cast(G, s)
def subclass_init(self, cls: type[t.Any]) -> None:
pass # fully opt out of instance_init
| (default_value: Any = traitlets.Undefined, allow_none: bool = False, read_only: bool = None, help: 'str | None' = None, config: 't.Any' = None, **kwargs: 't.Any') -> 'None' |
15,284 | traitlets.traitlets | validate | null | def validate(self, obj: t.Any, value: t.Any) -> G:
if isinstance(value, str):
return t.cast(G, value)
if isinstance(value, bytes):
try:
return t.cast(G, value.decode("ascii", "strict"))
except UnicodeDecodeError as e:
msg = "Could not decode {!r} for unicode trait '{}' of {} instance."
raise TraitError(msg.format(value, self.name, class_of(obj))) from e
self.error(obj, value)
| (self, obj: Any, value: Any) -> ~G |
15,285 | traitlets.traitlets | Union | A trait type representing a Union type. | class Union(TraitType[t.Any, t.Any]):
"""A trait type representing a Union type."""
def __init__(self, trait_types: t.Any, **kwargs: t.Any) -> None:
"""Construct a Union trait.
This trait allows values that are allowed by at least one of the
specified trait types. A Union traitlet cannot have metadata on
its own, besides the metadata of the listed types.
Parameters
----------
trait_types : sequence
The list of trait types of length at least 1.
**kwargs
Extra kwargs passed to `TraitType`
Notes
-----
Union([Float(), Bool(), Int()]) attempts to validate the provided values
with the validation function of Float, then Bool, and finally Int.
Parsing from string is ambiguous for container types which accept other
collection-like literals (e.g. List accepting both `[]` and `()`
precludes Union from ever parsing ``Union([List(), Tuple()])`` as a tuple;
you can modify behaviour of too permissive container traits by overriding
``_literal_from_string_pairs`` in subclasses.
Similarly, parsing unions of numeric types is only unambiguous if
types are provided in order of increasing permissiveness, e.g.
``Union([Int(), Float()])`` (since floats accept integer-looking values).
"""
self.trait_types = list(trait_types)
self.info_text = " or ".join([tt.info() for tt in self.trait_types])
super().__init__(**kwargs)
def default(self, obj: t.Any = None) -> t.Any:
default = super().default(obj)
for trait in self.trait_types:
if default is Undefined:
default = trait.default(obj)
else:
break
return default
def class_init(self, cls: type[HasTraits], name: str | None) -> None:
for trait_type in reversed(self.trait_types):
trait_type.class_init(cls, None)
super().class_init(cls, name)
def subclass_init(self, cls: type[t.Any]) -> None:
for trait_type in reversed(self.trait_types):
trait_type.subclass_init(cls)
# explicitly not calling super().subclass_init(cls)
# to opt out of instance_init
def validate(self, obj: t.Any, value: t.Any) -> t.Any:
with obj.cross_validation_lock:
for trait_type in self.trait_types:
try:
v = trait_type._validate(obj, value)
# In the case of an element trait, the name is None
if self.name is not None:
setattr(obj, "_" + self.name + "_metadata", trait_type.metadata)
return v
except TraitError:
continue
self.error(obj, value)
def __or__(self, other: t.Any) -> Union:
if isinstance(other, Union):
return Union(self.trait_types + other.trait_types)
else:
return Union([*self.trait_types, other])
def from_string(self, s: str) -> t.Any:
for trait_type in self.trait_types:
try:
v = trait_type.from_string(s)
return trait_type.validate(None, v)
except (TraitError, ValueError):
continue
return super().from_string(s)
| (trait_types: 't.Any', **kwargs: 't.Any') -> 'None' |
15,287 | traitlets.traitlets | __init__ | Construct a Union trait.
This trait allows values that are allowed by at least one of the
specified trait types. A Union traitlet cannot have metadata on
its own, besides the metadata of the listed types.
Parameters
----------
trait_types : sequence
The list of trait types of length at least 1.
**kwargs
Extra kwargs passed to `TraitType`
Notes
-----
Union([Float(), Bool(), Int()]) attempts to validate the provided values
with the validation function of Float, then Bool, and finally Int.
Parsing from string is ambiguous for container types which accept other
collection-like literals (e.g. List accepting both `[]` and `()`
precludes Union from ever parsing ``Union([List(), Tuple()])`` as a tuple;
you can modify behaviour of too permissive container traits by overriding
``_literal_from_string_pairs`` in subclasses.
Similarly, parsing unions of numeric types is only unambiguous if
types are provided in order of increasing permissiveness, e.g.
``Union([Int(), Float()])`` (since floats accept integer-looking values).
| def __init__(self, trait_types: t.Any, **kwargs: t.Any) -> None:
"""Construct a Union trait.
This trait allows values that are allowed by at least one of the
specified trait types. A Union traitlet cannot have metadata on
its own, besides the metadata of the listed types.
Parameters
----------
trait_types : sequence
The list of trait types of length at least 1.
**kwargs
Extra kwargs passed to `TraitType`
Notes
-----
Union([Float(), Bool(), Int()]) attempts to validate the provided values
with the validation function of Float, then Bool, and finally Int.
Parsing from string is ambiguous for container types which accept other
collection-like literals (e.g. List accepting both `[]` and `()`
precludes Union from ever parsing ``Union([List(), Tuple()])`` as a tuple;
you can modify behaviour of too permissive container traits by overriding
``_literal_from_string_pairs`` in subclasses.
Similarly, parsing unions of numeric types is only unambiguous if
types are provided in order of increasing permissiveness, e.g.
``Union([Int(), Float()])`` (since floats accept integer-looking values).
"""
self.trait_types = list(trait_types)
self.info_text = " or ".join([tt.info() for tt in self.trait_types])
super().__init__(**kwargs)
| (self, trait_types: Any, **kwargs: Any) -> NoneType |
15,288 | traitlets.traitlets | __or__ | null | def __or__(self, other: t.Any) -> Union:
if isinstance(other, Union):
return Union(self.trait_types + other.trait_types)
else:
return Union([*self.trait_types, other])
| (self, other: Any) -> traitlets.traitlets.Union |
15,292 | traitlets.traitlets | class_init | null | def class_init(self, cls: type[HasTraits], name: str | None) -> None:
for trait_type in reversed(self.trait_types):
trait_type.class_init(cls, None)
super().class_init(cls, name)
| (self, cls: type[traitlets.traitlets.HasTraits], name: str | None) -> NoneType |
15,293 | traitlets.traitlets | default | null | def default(self, obj: t.Any = None) -> t.Any:
default = super().default(obj)
for trait in self.trait_types:
if default is Undefined:
default = trait.default(obj)
else:
break
return default
| (self, obj: Optional[Any] = None) -> Any |
15,296 | traitlets.traitlets | from_string | null | def from_string(self, s: str) -> t.Any:
for trait_type in self.trait_types:
try:
v = trait_type.from_string(s)
return trait_type.validate(None, v)
except (TraitError, ValueError):
continue
return super().from_string(s)
| (self, s: str) -> Any |
15,305 | traitlets.traitlets | subclass_init | null | def subclass_init(self, cls: type[t.Any]) -> None:
for trait_type in reversed(self.trait_types):
trait_type.subclass_init(cls)
# explicitly not calling super().subclass_init(cls)
# to opt out of instance_init
| (self, cls: type[typing.Any]) -> NoneType |
15,307 | traitlets.traitlets | validate | null | def validate(self, obj: t.Any, value: t.Any) -> t.Any:
with obj.cross_validation_lock:
for trait_type in self.trait_types:
try:
v = trait_type._validate(obj, value)
# In the case of an element trait, the name is None
if self.name is not None:
setattr(obj, "_" + self.name + "_metadata", trait_type.metadata)
return v
except TraitError:
continue
self.error(obj, value)
| (self, obj: Any, value: Any) -> Any |
15,308 | ipyleaflet.leaflet | VectorLayer | VectorLayer abstract class. | class VectorLayer(Layer):
"""VectorLayer abstract class."""
_view_name = Unicode("LeafletVectorLayerView").tag(sync=True)
_model_name = Unicode("LeafletVectorLayerModel").tag(sync=True)
| (*args: 't.Any', **kwargs: 't.Any') -> 't.Any' |
15,373 | ipyleaflet.leaflet | VectorTileLayer | VectorTileLayer class, with Layer as parent class.
Vector tile layer.
Attributes
----------
url: string, default ""
Url to the vector tile service.
attribution: string, default ""
Vector tile service attribution.
vector_tile_layer_styles: dict, default {}
CSS Styles to apply to the vector data.
| class VectorTileLayer(Layer):
"""VectorTileLayer class, with Layer as parent class.
Vector tile layer.
Attributes
----------
url: string, default ""
Url to the vector tile service.
attribution: string, default ""
Vector tile service attribution.
vector_tile_layer_styles: dict, default {}
CSS Styles to apply to the vector data.
"""
_view_name = Unicode("LeafletVectorTileLayerView").tag(sync=True)
_model_name = Unicode("LeafletVectorTileLayerModel").tag(sync=True)
url = Unicode().tag(sync=True, o=True)
attribution = Unicode().tag(sync=True, o=True)
vector_tile_layer_styles = Dict().tag(sync=True, o=True)
def redraw(self):
"""Force redrawing the tiles.
This is especially useful when you are sure the server updated the tiles and you
need to refresh the layer.
"""
self.send({"msg": "redraw"})
| (*args: 't.Any', **kwargs: 't.Any') -> 't.Any' |
15,439 | ipyleaflet.leaflet | VideoOverlay | VideoOverlay class.
Video layer from a local or remote video file.
Attributes
----------
url: string, default ""
Url to the local or remote video file.
bounds: list, default [0., 0]
SW and NE corners of the video.
attribution: string, default ""
Video attribution.
| class VideoOverlay(RasterLayer):
"""VideoOverlay class.
Video layer from a local or remote video file.
Attributes
----------
url: string, default ""
Url to the local or remote video file.
bounds: list, default [0., 0]
SW and NE corners of the video.
attribution: string, default ""
Video attribution.
"""
_view_name = Unicode("LeafletVideoOverlayView").tag(sync=True)
_model_name = Unicode("LeafletVideoOverlayModel").tag(sync=True)
url = Unicode().tag(sync=True)
bounds = List([def_loc, def_loc], help="SW and NE corners of the image").tag(
sync=True
)
# Options
attribution = Unicode().tag(sync=True, o=True)
| (*args: 't.Any', **kwargs: 't.Any') -> 't.Any' |
15,504 | ipyleaflet.leaflet | WKTLayer | WKTLayer class.
Layer created from a local WKT file or WKT string input.
Attributes
----------
path: string, default ""
file path of local WKT file.
wkt_string: string, default ""
WKT string.
| class WKTLayer(GeoJSON):
"""WKTLayer class.
Layer created from a local WKT file or WKT string input.
Attributes
----------
path: string, default ""
file path of local WKT file.
wkt_string: string, default ""
WKT string.
"""
path = Unicode("")
wkt_string = Unicode("")
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.data = self._get_data()
@observe("path", "wkt_string", "style", "style_callback")
def _update_data(self, change):
self.data = self._get_data()
def _get_data(self):
try:
from shapely import geometry, wkt
except ImportError:
raise RuntimeError(
"The WKTLayer needs shapely to be installed, please run `pip install shapely`"
)
if self.path:
with open(self.path) as f:
parsed_wkt = wkt.load(f)
elif self.wkt_string:
parsed_wkt = wkt.loads(self.wkt_string)
else:
raise ValueError("Please provide either WKT file path or WKT string")
geo = geometry.mapping(parsed_wkt)
if geo["type"] == "GeometryCollection":
features = [
{"geometry": g, "properties": {}, "type": "Feature"}
for g in geo["geometries"]
]
feature_collection = {"type": "FeatureCollection", "features": features}
return feature_collection
else:
feature = {"geometry": geo, "properties": {}, "type": "Feature"}
return feature
| (**kwargs) |
15,509 | ipyleaflet.leaflet | __init__ | null | def __init__(self, **kwargs):
super().__init__(**kwargs)
self.data = self._get_data()
| (self, **kwargs) |
15,518 | ipyleaflet.leaflet | _get_data | null | def _get_data(self):
try:
from shapely import geometry, wkt
except ImportError:
raise RuntimeError(
"The WKTLayer needs shapely to be installed, please run `pip install shapely`"
)
if self.path:
with open(self.path) as f:
parsed_wkt = wkt.load(f)
elif self.wkt_string:
parsed_wkt = wkt.loads(self.wkt_string)
else:
raise ValueError("Please provide either WKT file path or WKT string")
geo = geometry.mapping(parsed_wkt)
if geo["type"] == "GeometryCollection":
features = [
{"geometry": g, "properties": {}, "type": "Feature"}
for g in geo["geometries"]
]
feature_collection = {"type": "FeatureCollection", "features": features}
return feature_collection
else:
feature = {"geometry": geo, "properties": {}, "type": "Feature"}
return feature
| (self) |
15,580 | ipyleaflet.leaflet | WMSLayer | WMSLayer class, with TileLayer as a parent class.
Attributes
----------
layers: string, default ""
Comma-separated list of WMS layers to show.
styles: string, default ""
Comma-separated list of WMS styles
format: string, default "image/jpeg"
WMS image format (use `'image/png'` for layers with transparency).
transparent: boolean, default False
If true, the WMS service will return images with transparency.
crs: dict, default ipyleaflet.projections.EPSG3857
Projection used for this WMS service.
| class WMSLayer(TileLayer):
"""WMSLayer class, with TileLayer as a parent class.
Attributes
----------
layers: string, default ""
Comma-separated list of WMS layers to show.
styles: string, default ""
Comma-separated list of WMS styles
format: string, default "image/jpeg"
WMS image format (use `'image/png'` for layers with transparency).
transparent: boolean, default False
If true, the WMS service will return images with transparency.
crs: dict, default ipyleaflet.projections.EPSG3857
Projection used for this WMS service.
"""
_view_name = Unicode("LeafletWMSLayerView").tag(sync=True)
_model_name = Unicode("LeafletWMSLayerModel").tag(sync=True)
# Options
layers = Unicode().tag(sync=True, o=True)
styles = Unicode().tag(sync=True, o=True)
format = Unicode("image/jpeg").tag(sync=True, o=True)
transparent = Bool(False).tag(sync=True, o=True)
crs = Dict(default_value=projections.EPSG3857).tag(sync=True)
uppercase = Bool(False).tag(sync=True, o=True)
| (*args: 't.Any', **kwargs: 't.Any') -> 't.Any' |
15,648 | ipywidgets.widgets.widget | Widget | null | class Widget(LoggingHasTraits):
#-------------------------------------------------------------------------
# Class attributes
#-------------------------------------------------------------------------
_widget_construction_callback = None
_control_comm = None
@_staticproperty
def widgets():
# Because this is a static attribute, it will be accessed when initializing this class. In that case, since a user
# did not explicitly try to use this attribute, we do not want to throw a deprecation warning.
# So we check if the thing calling this static property is one of the known initialization functions in traitlets.
frame = _get_frame(2)
if not (frame.f_code.co_filename == TRAITLETS_FILE and (frame.f_code.co_name in ('getmembers', 'setup_instance', 'setup_class'))):
deprecation("Widget.widgets is deprecated.")
return _instances
@_staticproperty
def _active_widgets():
# Because this is a static attribute, it will be accessed when initializing this class. In that case, since a user
# did not explicitly try to use this attribute, we do not want to throw a deprecation warning.
# So we check if the thing calling this static property is one of the known initialization functions in traitlets.
frame = _get_frame(2)
if not (frame.f_code.co_filename == TRAITLETS_FILE and (frame.f_code.co_name in ('getmembers', 'setup_instance', 'setup_class'))):
deprecation("Widget._active_widgets is deprecated.")
return _instances
@_staticproperty
def _widget_types():
# Because this is a static attribute, it will be accessed when initializing this class. In that case, since a user
# did not explicitly try to use this attribute, we do not want to throw a deprecation warning.
# So we check if the thing calling this static property is one of the known initialization functions in traitlets.
frame = _get_frame(2)
if not (frame.f_code.co_filename == TRAITLETS_FILE and (frame.f_code.co_name in ('getmembers', 'setup_instance', 'setup_class'))):
deprecation("Widget._widget_types is deprecated.")
return _registry
@_staticproperty
def widget_types():
# Because this is a static attribute, it will be accessed when initializing this class. In that case, since a user
# did not explicitly try to use this attribute, we do not want to throw a deprecation warning.
# So we check if the thing calling this static property is one of the known initialization functions in traitlets.
frame = _get_frame(2)
if not (frame.f_code.co_filename == TRAITLETS_FILE and (frame.f_code.co_name in ('getmembers', 'setup_instance', 'setup_class'))):
deprecation("Widget.widget_types is deprecated.")
return _registry
@classmethod
def close_all(cls):
for widget in list(_instances.values()):
widget.close()
@staticmethod
def on_widget_constructed(callback):
"""Registers a callback to be called when a widget is constructed.
The callback must have the following signature:
callback(widget)"""
Widget._widget_construction_callback = callback
@staticmethod
def _call_widget_constructed(widget):
"""Static method, called when a widget is constructed."""
if Widget._widget_construction_callback is not None and callable(Widget._widget_construction_callback):
Widget._widget_construction_callback(widget)
@classmethod
def handle_control_comm_opened(cls, comm, msg):
"""
Class method, called when the comm-open message on the
"jupyter.widget.control" comm channel is received
"""
version = msg.get('metadata', {}).get('version', '')
if version.split('.')[0] != CONTROL_PROTOCOL_VERSION_MAJOR:
raise ValueError("Incompatible widget control protocol versions: received version %r, expected version %r"%(version, __control_protocol_version__))
cls._control_comm = comm
cls._control_comm.on_msg(cls._handle_control_comm_msg)
@classmethod
def _handle_control_comm_msg(cls, msg):
# This shouldn't happen unless someone calls this method manually
if cls._control_comm is None:
raise RuntimeError('Control comm has not been properly opened')
data = msg['content']['data']
method = data['method']
if method == 'request_states':
# Send back the full widgets state
cls.get_manager_state()
widgets = _instances.values()
full_state = {}
drop_defaults = False
for widget in widgets:
full_state[widget.model_id] = {
'model_name': widget._model_name,
'model_module': widget._model_module,
'model_module_version': widget._model_module_version,
'state': widget.get_state(drop_defaults=drop_defaults),
}
full_state, buffer_paths, buffers = _remove_buffers(full_state)
cls._control_comm.send(dict(
method='update_states',
states=full_state,
buffer_paths=buffer_paths
), buffers=buffers)
else:
raise RuntimeError('Unknown front-end to back-end widget control msg with method "%s"' % method)
@staticmethod
def handle_comm_opened(comm, msg):
"""Static method, called when a widget is constructed."""
version = msg.get('metadata', {}).get('version', '')
if version.split('.')[0] != PROTOCOL_VERSION_MAJOR:
raise ValueError("Incompatible widget protocol versions: received version %r, expected version %r"%(version, __protocol_version__))
data = msg['content']['data']
state = data['state']
# Find the widget class to instantiate in the registered widgets
widget_class = _registry.get(state['_model_module'],
state['_model_module_version'],
state['_model_name'],
state['_view_module'],
state['_view_module_version'],
state['_view_name'])
widget = widget_class(comm=comm)
if 'buffer_paths' in data:
_put_buffers(state, data['buffer_paths'], msg['buffers'])
widget.set_state(state)
@staticmethod
def get_manager_state(drop_defaults=False, widgets=None):
"""Returns the full state for a widget manager for embedding
:param drop_defaults: when True, it will not include default value
:param widgets: list with widgets to include in the state (or all widgets when None)
:return:
"""
state = {}
if widgets is None:
widgets = _instances.values()
for widget in widgets:
state[widget.model_id] = widget._get_embed_state(drop_defaults=drop_defaults)
return {'version_major': 2, 'version_minor': 0, 'state': state}
def _get_embed_state(self, drop_defaults=False):
state = {
'model_name': self._model_name,
'model_module': self._model_module,
'model_module_version': self._model_module_version
}
model_state, buffer_paths, buffers = _remove_buffers(self.get_state(drop_defaults=drop_defaults))
state['state'] = model_state
if len(buffers) > 0:
state['buffers'] = [{'encoding': 'base64',
'path': p,
'data': standard_b64encode(d).decode('ascii')}
for p, d in zip(buffer_paths, buffers)]
return state
def get_view_spec(self):
return dict(version_major=2, version_minor=0, model_id=self._model_id)
#-------------------------------------------------------------------------
# Traits
#-------------------------------------------------------------------------
_model_name = Unicode('WidgetModel',
help="Name of the model.", read_only=True).tag(sync=True)
_model_module = Unicode('@jupyter-widgets/base',
help="The namespace for the model.", read_only=True).tag(sync=True)
_model_module_version = Unicode(__jupyter_widgets_base_version__,
help="A semver requirement for namespace version containing the model.", read_only=True).tag(sync=True)
_view_name = Unicode(None, allow_none=True,
help="Name of the view.").tag(sync=True)
_view_module = Unicode(None, allow_none=True,
help="The namespace for the view.").tag(sync=True)
_view_module_version = Unicode('',
help="A semver requirement for the namespace version containing the view.").tag(sync=True)
_view_count = Int(None, allow_none=True,
help="EXPERIMENTAL: The number of views of the model displayed in the frontend. This attribute is experimental and may change or be removed in the future. None signifies that views will not be tracked. Set this to 0 to start tracking view creation/deletion.").tag(sync=True)
comm = Any(allow_none=True)
keys = List(help="The traits which are synced.")
@default('keys')
def _default_keys(self):
return [name for name in self.traits(sync=True)]
_property_lock = Dict()
_holding_sync = False
_states_to_send = Set()
_msg_callbacks = Instance(CallbackDispatcher, ())
#-------------------------------------------------------------------------
# (Con/de)structor
#-------------------------------------------------------------------------
def __init__(self, **kwargs):
"""Public constructor"""
self._model_id = kwargs.pop('model_id', None)
super().__init__(**kwargs)
Widget._call_widget_constructed(self)
self.open()
def __copy__(self):
raise NotImplementedError("Widgets cannot be copied; custom implementation required")
def __deepcopy__(self, memo):
raise NotImplementedError("Widgets cannot be copied; custom implementation required")
def __del__(self):
"""Object disposal"""
self.close()
#-------------------------------------------------------------------------
# Properties
#-------------------------------------------------------------------------
def open(self):
"""Open a comm to the frontend if one isn't already open."""
if self.comm is None:
state, buffer_paths, buffers = _remove_buffers(self.get_state())
args = dict(target_name='jupyter.widget',
data={'state': state, 'buffer_paths': buffer_paths},
buffers=buffers,
metadata={'version': __protocol_version__}
)
if self._model_id is not None:
args['comm_id'] = self._model_id
self.comm = comm.create_comm(**args)
@observe('comm')
def _comm_changed(self, change):
"""Called when the comm is changed."""
if change['new'] is None:
return
self._model_id = self.model_id
self.comm.on_msg(self._handle_msg)
_instances[self.model_id] = self
@property
def model_id(self):
"""Gets the model id of this widget.
If a Comm doesn't exist yet, a Comm will be created automagically."""
return self.comm.comm_id
#-------------------------------------------------------------------------
# Methods
#-------------------------------------------------------------------------
def close(self):
"""Close method.
Closes the underlying comm.
When the comm is closed, all of the widget views are automatically
removed from the front-end."""
if self.comm is not None:
_instances.pop(self.model_id, None)
self.comm.close()
self.comm = None
self._repr_mimebundle_ = None
def send_state(self, key=None):
"""Sends the widget state, or a piece of it, to the front-end, if it exists.
Parameters
----------
key : unicode, or iterable (optional)
A single property's name or iterable of property names to sync with the front-end.
"""
state = self.get_state(key=key)
if len(state) > 0:
if self._property_lock: # we need to keep this dict up to date with the front-end values
for name, value in state.items():
if name in self._property_lock:
self._property_lock[name] = value
state, buffer_paths, buffers = _remove_buffers(state)
msg = {'method': 'update', 'state': state, 'buffer_paths': buffer_paths}
self._send(msg, buffers=buffers)
def get_state(self, key=None, drop_defaults=False):
"""Gets the widget state, or a piece of it.
Parameters
----------
key : unicode or iterable (optional)
A single property's name or iterable of property names to get.
Returns
-------
state : dict of states
metadata : dict
metadata for each field: {key: metadata}
"""
if key is None:
keys = self.keys
elif isinstance(key, str):
keys = [key]
elif isinstance(key, Iterable):
keys = key
else:
raise ValueError("key must be a string, an iterable of keys, or None")
state = {}
traits = self.traits()
for k in keys:
to_json = self.trait_metadata(k, 'to_json', self._trait_to_json)
value = to_json(getattr(self, k), self)
if not drop_defaults or not self._compare(value, traits[k].default_value):
state[k] = value
return state
def _is_numpy(self, x):
return x.__class__.__name__ == 'ndarray' and x.__class__.__module__ == 'numpy'
def _compare(self, a, b):
if self._is_numpy(a) or self._is_numpy(b):
import numpy as np
return np.array_equal(a, b)
else:
return a == b
def set_state(self, sync_data):
"""Called when a state is received from the front-end."""
# Send an echo update message immediately
if JUPYTER_WIDGETS_ECHO:
echo_state = {}
for attr, value in sync_data.items():
if attr in self.keys and self.trait_metadata(attr, 'echo_update', default=True):
echo_state[attr] = value
if echo_state:
echo_state, echo_buffer_paths, echo_buffers = _remove_buffers(echo_state)
msg = {
'method': 'echo_update',
'state': echo_state,
'buffer_paths': echo_buffer_paths,
}
self._send(msg, buffers=echo_buffers)
# The order of these context managers is important. Properties must
# be locked when the hold_trait_notification context manager is
# released and notifications are fired.
with self._lock_property(**sync_data), self.hold_trait_notifications():
for name in sync_data:
if name in self.keys:
from_json = self.trait_metadata(name, 'from_json',
self._trait_from_json)
self.set_trait(name, from_json(sync_data[name], self))
def send(self, content, buffers=None):
"""Sends a custom msg to the widget model in the front-end.
Parameters
----------
content : dict
Content of the message to send.
buffers : list of binary buffers
Binary buffers to send with message
"""
self._send({"method": "custom", "content": content}, buffers=buffers)
def on_msg(self, callback, remove=False):
"""(Un)Register a custom msg receive callback.
Parameters
----------
callback: callable
callback will be passed three arguments when a message arrives::
callback(widget, content, buffers)
remove: bool
True if the callback should be unregistered."""
self._msg_callbacks.register_callback(callback, remove=remove)
def add_traits(self, **traits):
"""Dynamically add trait attributes to the Widget."""
super().add_traits(**traits)
for name, trait in traits.items():
if trait.get_metadata('sync'):
self.keys.append(name)
self.send_state(name)
def notify_change(self, change):
"""Called when a property has changed."""
# Send the state to the frontend before the user-registered callbacks
# are called.
name = change['name']
if self.comm is not None and getattr(self.comm, 'kernel', True) is not None:
# Make sure this isn't information that the front-end just sent us.
if name in self.keys and self._should_send_property(name, getattr(self, name)):
# Send new state to front-end
self.send_state(key=name)
super().notify_change(change)
def __repr__(self):
return self._gen_repr_from_keys(self._repr_keys())
#-------------------------------------------------------------------------
# Support methods
#-------------------------------------------------------------------------
@contextmanager
def _lock_property(self, **properties):
"""Lock a property-value pair.
The value should be the JSON state of the property.
NOTE: This, in addition to the single lock for all state changes, is
flawed. In the future we may want to look into buffering state changes
back to the front-end."""
self._property_lock = properties
try:
yield
finally:
self._property_lock = {}
@contextmanager
def hold_sync(self):
"""Hold syncing any state until the outermost context manager exits"""
if self._holding_sync is True:
yield
else:
try:
self._holding_sync = True
yield
finally:
self._holding_sync = False
self.send_state(self._states_to_send)
self._states_to_send.clear()
def _should_send_property(self, key, value):
"""Check the property lock (property_lock)"""
to_json = self.trait_metadata(key, 'to_json', self._trait_to_json)
if key in self._property_lock:
# model_state, buffer_paths, buffers
split_value = _remove_buffers({ key: to_json(value, self)})
split_lock = _remove_buffers({ key: self._property_lock[key]})
# A roundtrip conversion through json in the comparison takes care of
# idiosyncracies of how python data structures map to json, for example
# tuples get converted to lists.
if (jsonloads(jsondumps(split_value[0])) == split_lock[0]
and split_value[1] == split_lock[1]
and _buffer_list_equal(split_value[2], split_lock[2])):
if self._holding_sync:
self._states_to_send.discard(key)
return False
if self._holding_sync:
self._states_to_send.add(key)
return False
else:
return True
# Event handlers
@_show_traceback
def _handle_msg(self, msg):
"""Called when a msg is received from the front-end"""
data = msg['content']['data']
method = data['method']
if method == 'update':
if 'state' in data:
state = data['state']
if 'buffer_paths' in data:
_put_buffers(state, data['buffer_paths'], msg['buffers'])
self.set_state(state)
# Handle a state request.
elif method == 'request_state':
self.send_state()
# Handle a custom msg from the front-end.
elif method == 'custom':
if 'content' in data:
self._handle_custom_msg(data['content'], msg['buffers'])
# Catch remainder.
else:
self.log.error('Unknown front-end to back-end widget msg with method "%s"' % method)
def _handle_custom_msg(self, content, buffers):
"""Called when a custom msg is received."""
self._msg_callbacks(self, content, buffers)
@staticmethod
def _trait_to_json(x, self):
"""Convert a trait value to json."""
return x
@staticmethod
def _trait_from_json(x, self):
"""Convert json values to objects."""
return x
def _repr_mimebundle_(self, **kwargs):
plaintext = repr(self)
if len(plaintext) > 110:
plaintext = plaintext[:110] + '…'
data = {
'text/plain': plaintext,
}
if self._view_name is not None:
# The 'application/vnd.jupyter.widget-view+json' mimetype has not been registered yet.
# See the registration process and naming convention at
# http://tools.ietf.org/html/rfc6838
# and the currently registered mimetypes at
# http://www.iana.org/assignments/media-types/media-types.xhtml.
data['application/vnd.jupyter.widget-view+json'] = {
'version_major': 2,
'version_minor': 0,
'model_id': self._model_id
}
return data
def _send(self, msg, buffers=None):
"""Sends a message to the model in the front-end."""
if self.comm is not None and (self.comm.kernel is not None if hasattr(self.comm, "kernel") else True):
self.comm.send(data=msg, buffers=buffers)
def _repr_keys(self):
traits = self.traits()
for key in sorted(self.keys):
# Exclude traits that start with an underscore
if key[0] == '_':
continue
# Exclude traits who are equal to their default value
value = getattr(self, key)
trait = traits[key]
if self._compare(value, trait.default_value):
continue
elif (isinstance(trait, (Container, Dict)) and
trait.default_value == Undefined and
(value is None or len(value) == 0)):
# Empty container, and dynamic default will be empty
continue
yield key
def _gen_repr_from_keys(self, keys):
class_name = self.__class__.__name__
signature = ', '.join(
'{}={!r}'.format(key, getattr(self, key))
for key in keys
)
return '{}({})'.format(class_name, signature)
| (**kwargs) |
15,705 | ipyleaflet.leaflet | WidgetControl | WidgetControl class, with Control as parent class.
A control that contains any DOMWidget instance.
Attributes
----------
widget: DOMWidget
The widget to put inside of the control. It can be any widget, even coming from
a third-party library like bqplot.
| class WidgetControl(Control):
"""WidgetControl class, with Control as parent class.
A control that contains any DOMWidget instance.
Attributes
----------
widget: DOMWidget
The widget to put inside of the control. It can be any widget, even coming from
a third-party library like bqplot.
"""
_view_name = Unicode("LeafletWidgetControlView").tag(sync=True)
_model_name = Unicode("LeafletWidgetControlModel").tag(sync=True)
widget = Instance(DOMWidget).tag(sync=True, **widget_serialization)
max_width = Int(default_value=None, allow_none=True).tag(sync=True)
min_width = Int(default_value=None, allow_none=True).tag(sync=True)
max_height = Int(default_value=None, allow_none=True).tag(sync=True)
min_height = Int(default_value=None, allow_none=True).tag(sync=True)
transparent_bg = Bool(False).tag(sync=True, o=True)
| (*args: 't.Any', **kwargs: 't.Any') -> 't.Any' |
15,762 | ipyleaflet.leaflet | ZoomControl | ZoomControl class, with Control as parent class.
A control which contains buttons for zooming in/out the Map.
Attributes
----------
zoom_in_text: str, default '+'
Text to put in the zoom-in button.
zoom_in_title: str, default 'Zoom in'
Title to put in the zoom-in button, this is shown when the mouse
is over the button.
zoom_out_text: str, default '-'
Text to put in the zoom-out button.
zoom_out_title: str, default 'Zoom out'
Title to put in the zoom-out button, this is shown when the mouse
is over the button.
| class ZoomControl(Control):
"""ZoomControl class, with Control as parent class.
A control which contains buttons for zooming in/out the Map.
Attributes
----------
zoom_in_text: str, default '+'
Text to put in the zoom-in button.
zoom_in_title: str, default 'Zoom in'
Title to put in the zoom-in button, this is shown when the mouse
is over the button.
zoom_out_text: str, default '-'
Text to put in the zoom-out button.
zoom_out_title: str, default 'Zoom out'
Title to put in the zoom-out button, this is shown when the mouse
is over the button.
"""
_view_name = Unicode("LeafletZoomControlView").tag(sync=True)
_model_name = Unicode("LeafletZoomControlModel").tag(sync=True)
zoom_in_text = Unicode("+").tag(sync=True, o=True)
zoom_in_title = Unicode("Zoom in").tag(sync=True, o=True)
zoom_out_text = Unicode("-").tag(sync=True, o=True)
zoom_out_title = Unicode("Zoom out").tag(sync=True, o=True)
| (*args: 't.Any', **kwargs: 't.Any') -> 't.Any' |
15,821 | ipyleaflet.leaflet | basemap_to_tiles | Turn a basemap into a TileLayer object.
Parameters
----------
basemap : class:`xyzservices.lib.TileProvider` or Dict
Basemap description coming from ipyleaflet.basemaps.
day: string
If relevant for the chosen basemap, you can specify the day for
the tiles in the "%Y-%m-%d" format. Defaults to yesterday's date.
kwargs: key-word arguments
Extra key-word arguments to pass to the TileLayer constructor.
| def basemap_to_tiles(basemap, day=yesterday, **kwargs):
"""Turn a basemap into a TileLayer object.
Parameters
----------
basemap : class:`xyzservices.lib.TileProvider` or Dict
Basemap description coming from ipyleaflet.basemaps.
day: string
If relevant for the chosen basemap, you can specify the day for
the tiles in the "%Y-%m-%d" format. Defaults to yesterday's date.
kwargs: key-word arguments
Extra key-word arguments to pass to the TileLayer constructor.
"""
if isinstance(basemap, xyzservices.lib.TileProvider):
url = basemap.build_url(time=day)
elif isinstance(basemap, dict):
url = basemap.get("url", "")
else:
raise ValueError("Invalid basemap type")
return TileLayer(
url=url,
max_zoom=basemap.get("max_zoom", 18),
min_zoom=basemap.get("min_zoom", 1),
attribution=basemap.get("html_attribution", "")
or basemap.get("attribution", ""),
name=basemap.get("name", ""),
**kwargs,
)
| (basemap, day='2024-05-11', **kwargs) |
15,824 | traitlets.traitlets | default | A decorator which assigns a dynamic default for a Trait on a HasTraits object.
Parameters
----------
name
The str name of the Trait on the object whose default should be generated.
Notes
-----
Unlike observers and validators which are properties of the HasTraits
instance, default value generators are class-level properties.
Besides, default generators are only invoked if they are registered in
subclasses of `this_type`.
::
class A(HasTraits):
bar = Int()
@default('bar')
def get_bar_default(self):
return 11
class B(A):
bar = Float() # This trait ignores the default generator defined in
# the base class A
class C(B):
@default('bar')
def some_other_default(self): # This default generator should not be
return 3.0 # ignored since it is defined in a
# class derived from B.a.this_class.
| def default(name: str) -> DefaultHandler:
"""A decorator which assigns a dynamic default for a Trait on a HasTraits object.
Parameters
----------
name
The str name of the Trait on the object whose default should be generated.
Notes
-----
Unlike observers and validators which are properties of the HasTraits
instance, default value generators are class-level properties.
Besides, default generators are only invoked if they are registered in
subclasses of `this_type`.
::
class A(HasTraits):
bar = Int()
@default('bar')
def get_bar_default(self):
return 11
class B(A):
bar = Float() # This trait ignores the default generator defined in
# the base class A
class C(B):
@default('bar')
def some_other_default(self): # This default generator should not be
return 3.0 # ignored since it is defined in a
# class derived from B.a.this_class.
"""
if not isinstance(name, str):
raise TypeError("Trait name must be a string or All, not %r" % name)
return DefaultHandler(name)
| (name: str) -> traitlets.traitlets.DefaultHandler |
15,825 | IPython.core.display_functions | display | Display a Python object in all frontends.
By default all representations will be computed and sent to the frontends.
Frontends can decide which representation is used and how.
In terminal IPython this will be similar to using :func:`print`, for use in richer
frontends see Jupyter notebook examples with rich display logic.
Parameters
----------
*objs : object
The Python objects to display.
raw : bool, optional
Are the objects to be displayed already mimetype-keyed dicts of raw display data,
or Python objects that need to be formatted before display? [default: False]
include : list, tuple or set, optional
A list of format type strings (MIME types) to include in the
format data dict. If this is set *only* the format types included
in this list will be computed.
exclude : list, tuple or set, optional
A list of format type strings (MIME types) to exclude in the format
data dict. If this is set all format types will be computed,
except for those included in this argument.
metadata : dict, optional
A dictionary of metadata to associate with the output.
mime-type keys in this dictionary will be associated with the individual
representation formats, if they exist.
transient : dict, optional
A dictionary of transient data to associate with the output.
Data in this dict should not be persisted to files (e.g. notebooks).
display_id : str, bool optional
Set an id for the display.
This id can be used for updating this display area later via update_display.
If given as `True`, generate a new `display_id`
clear : bool, optional
Should the output area be cleared before displaying anything? If True,
this will wait for additional output before clearing. [default: False]
**kwargs : additional keyword-args, optional
Additional keyword-arguments are passed through to the display publisher.
Returns
-------
handle: DisplayHandle
Returns a handle on updatable displays for use with :func:`update_display`,
if `display_id` is given. Returns :any:`None` if no `display_id` is given
(default).
Examples
--------
>>> class Json(object):
... def __init__(self, json):
... self.json = json
... def _repr_pretty_(self, pp, cycle):
... import json
... pp.text(json.dumps(self.json, indent=2))
... def __repr__(self):
... return str(self.json)
...
>>> d = Json({1:2, 3: {4:5}})
>>> print(d)
{1: 2, 3: {4: 5}}
>>> display(d)
{
"1": 2,
"3": {
"4": 5
}
}
>>> def int_formatter(integer, pp, cycle):
... pp.text('I'*integer)
>>> plain = get_ipython().display_formatter.formatters['text/plain']
>>> plain.for_type(int, int_formatter)
<function _repr_pprint at 0x...>
>>> display(7-5)
II
>>> del plain.type_printers[int]
>>> display(7-5)
2
See Also
--------
:func:`update_display`
Notes
-----
In Python, objects can declare their textual representation using the
`__repr__` method. IPython expands on this idea and allows objects to declare
other, rich representations including:
- HTML
- JSON
- PNG
- JPEG
- SVG
- LaTeX
A single object can declare some or all of these representations; all are
handled by IPython's display system.
The main idea of the first approach is that you have to implement special
display methods when you define your class, one for each representation you
want to use. Here is a list of the names of the special methods and the
values they must return:
- `_repr_html_`: return raw HTML as a string, or a tuple (see below).
- `_repr_json_`: return a JSONable dict, or a tuple (see below).
- `_repr_jpeg_`: return raw JPEG data, or a tuple (see below).
- `_repr_png_`: return raw PNG data, or a tuple (see below).
- `_repr_svg_`: return raw SVG data as a string, or a tuple (see below).
- `_repr_latex_`: return LaTeX commands in a string surrounded by "$",
or a tuple (see below).
- `_repr_mimebundle_`: return a full mimebundle containing the mapping
from all mimetypes to data.
Use this for any mime-type not listed above.
The above functions may also return the object's metadata alonside the
data. If the metadata is available, the functions will return a tuple
containing the data and metadata, in that order. If there is no metadata
available, then the functions will return the data only.
When you are directly writing your own classes, you can adapt them for
display in IPython by following the above approach. But in practice, you
often need to work with existing classes that you can't easily modify.
You can refer to the documentation on integrating with the display system in
order to register custom formatters for already existing types
(:ref:`integrating_rich_display`).
.. versionadded:: 5.4 display available without import
.. versionadded:: 6.1 display available without import
Since IPython 5.4 and 6.1 :func:`display` is automatically made available to
the user without import. If you are using display in a document that might
be used in a pure python context or with older version of IPython, use the
following import at the top of your file::
from IPython.display import display
| def display(
*objs,
include=None,
exclude=None,
metadata=None,
transient=None,
display_id=None,
raw=False,
clear=False,
**kwargs,
):
"""Display a Python object in all frontends.
By default all representations will be computed and sent to the frontends.
Frontends can decide which representation is used and how.
In terminal IPython this will be similar to using :func:`print`, for use in richer
frontends see Jupyter notebook examples with rich display logic.
Parameters
----------
*objs : object
The Python objects to display.
raw : bool, optional
Are the objects to be displayed already mimetype-keyed dicts of raw display data,
or Python objects that need to be formatted before display? [default: False]
include : list, tuple or set, optional
A list of format type strings (MIME types) to include in the
format data dict. If this is set *only* the format types included
in this list will be computed.
exclude : list, tuple or set, optional
A list of format type strings (MIME types) to exclude in the format
data dict. If this is set all format types will be computed,
except for those included in this argument.
metadata : dict, optional
A dictionary of metadata to associate with the output.
mime-type keys in this dictionary will be associated with the individual
representation formats, if they exist.
transient : dict, optional
A dictionary of transient data to associate with the output.
Data in this dict should not be persisted to files (e.g. notebooks).
display_id : str, bool optional
Set an id for the display.
This id can be used for updating this display area later via update_display.
If given as `True`, generate a new `display_id`
clear : bool, optional
Should the output area be cleared before displaying anything? If True,
this will wait for additional output before clearing. [default: False]
**kwargs : additional keyword-args, optional
Additional keyword-arguments are passed through to the display publisher.
Returns
-------
handle: DisplayHandle
Returns a handle on updatable displays for use with :func:`update_display`,
if `display_id` is given. Returns :any:`None` if no `display_id` is given
(default).
Examples
--------
>>> class Json(object):
... def __init__(self, json):
... self.json = json
... def _repr_pretty_(self, pp, cycle):
... import json
... pp.text(json.dumps(self.json, indent=2))
... def __repr__(self):
... return str(self.json)
...
>>> d = Json({1:2, 3: {4:5}})
>>> print(d)
{1: 2, 3: {4: 5}}
>>> display(d)
{
"1": 2,
"3": {
"4": 5
}
}
>>> def int_formatter(integer, pp, cycle):
... pp.text('I'*integer)
>>> plain = get_ipython().display_formatter.formatters['text/plain']
>>> plain.for_type(int, int_formatter)
<function _repr_pprint at 0x...>
>>> display(7-5)
II
>>> del plain.type_printers[int]
>>> display(7-5)
2
See Also
--------
:func:`update_display`
Notes
-----
In Python, objects can declare their textual representation using the
`__repr__` method. IPython expands on this idea and allows objects to declare
other, rich representations including:
- HTML
- JSON
- PNG
- JPEG
- SVG
- LaTeX
A single object can declare some or all of these representations; all are
handled by IPython's display system.
The main idea of the first approach is that you have to implement special
display methods when you define your class, one for each representation you
want to use. Here is a list of the names of the special methods and the
values they must return:
- `_repr_html_`: return raw HTML as a string, or a tuple (see below).
- `_repr_json_`: return a JSONable dict, or a tuple (see below).
- `_repr_jpeg_`: return raw JPEG data, or a tuple (see below).
- `_repr_png_`: return raw PNG data, or a tuple (see below).
- `_repr_svg_`: return raw SVG data as a string, or a tuple (see below).
- `_repr_latex_`: return LaTeX commands in a string surrounded by "$",
or a tuple (see below).
- `_repr_mimebundle_`: return a full mimebundle containing the mapping
from all mimetypes to data.
Use this for any mime-type not listed above.
The above functions may also return the object's metadata alonside the
data. If the metadata is available, the functions will return a tuple
containing the data and metadata, in that order. If there is no metadata
available, then the functions will return the data only.
When you are directly writing your own classes, you can adapt them for
display in IPython by following the above approach. But in practice, you
often need to work with existing classes that you can't easily modify.
You can refer to the documentation on integrating with the display system in
order to register custom formatters for already existing types
(:ref:`integrating_rich_display`).
.. versionadded:: 5.4 display available without import
.. versionadded:: 6.1 display available without import
Since IPython 5.4 and 6.1 :func:`display` is automatically made available to
the user without import. If you are using display in a document that might
be used in a pure python context or with older version of IPython, use the
following import at the top of your file::
from IPython.display import display
"""
from IPython.core.interactiveshell import InteractiveShell
if not InteractiveShell.initialized():
# Directly print objects.
print(*objs)
return
if transient is None:
transient = {}
if metadata is None:
metadata={}
if display_id:
if display_id is True:
display_id = _new_id()
transient['display_id'] = display_id
if kwargs.get('update') and 'display_id' not in transient:
raise TypeError('display_id required for update_display')
if transient:
kwargs['transient'] = transient
if not objs and display_id:
# if given no objects, but still a request for a display_id,
# we assume the user wants to insert an empty output that
# can be updated later
objs = [{}]
raw = True
if not raw:
format = InteractiveShell.instance().display_formatter.format
if clear:
clear_output(wait=True)
for obj in objs:
if raw:
publish_display_data(data=obj, metadata=metadata, **kwargs)
else:
format_dict, md_dict = format(obj, include=include, exclude=exclude)
if not format_dict:
# nothing to display (e.g. _ipython_display_ took over)
continue
if metadata:
# kwarg-specified metadata gets precedence
_merge(md_dict, metadata)
publish_display_data(data=format_dict, metadata=md_dict, **kwargs)
if display_id:
return DisplayHandle(display_id)
| (*objs, include=None, exclude=None, metadata=None, transient=None, display_id=None, raw=False, clear=False, **kwargs) |
15,826 | ipywidgets.embed | embed_minimal_html | Write a minimal HTML file with widget views embedded.
Parameters
----------
fp: filename or file-like object
The file to write the HTML output to.
views: widget or collection of widgets or None
The widgets to include views for. If None, all DOMWidgets are
included (not just the displayed ones).
title: title of the html page.
template: Template in which to embed the widget state.
This should be a Python string with placeholders
`{title}` and `{snippet}`. The `{snippet}` placeholder
will be replaced by all the widgets.
drop_defaults: boolean
Whether to drop default values from the widget states.
state: dict or None (default)
The state to include. When set to None, the state of all widgets
know to the widget manager is included. Otherwise it uses the
passed state directly. This allows for end users to include a
smaller state, under the responsibility that this state is
sufficient to reconstruct the embedded views.
indent: integer, string or None
The indent to use for the JSON state dump. See `json.dumps` for
full description.
embed_url: string or None
Allows for overriding the URL used to fetch the widget manager
for the embedded code. This defaults (None) to a `jsDelivr` CDN url.
requirejs: boolean (True)
Enables the requirejs-based embedding, which allows for custom widgets.
If True, the embed_url should point to an AMD module.
cors: boolean (True)
If True avoids sending user credentials while requesting the scripts.
When opening an HTML file from disk, some browsers may refuse to load
the scripts.
| @doc_subst(_doc_snippets)
def embed_minimal_html(fp, views, title='IPyWidget export', template=None, **kwargs):
"""Write a minimal HTML file with widget views embedded.
Parameters
----------
fp: filename or file-like object
The file to write the HTML output to.
{views_attribute}
title: title of the html page.
template: Template in which to embed the widget state.
This should be a Python string with placeholders
`{{title}}` and `{{snippet}}`. The `{{snippet}}` placeholder
will be replaced by all the widgets.
{embed_kwargs}
"""
snippet = embed_snippet(views, **kwargs)
values = {
'title': title,
'snippet': snippet,
}
if template is None:
template = html_template
html_code = template.format(**values)
# Check if fp is writable:
if hasattr(fp, 'write'):
fp.write(html_code)
else:
# Assume fp is a filename:
with open(fp, "w") as f:
f.write(html_code)
| (fp, views, title='IPyWidget export', template=None, **kwargs) |
15,827 | ipywidgets.widgets.interaction | interactive |
A VBox container containing a group of interactive widgets tied to a
function.
Parameters
----------
__interact_f : function
The function to which the interactive widgets are tied. The `**kwargs`
should match the function signature.
__options : dict
A dict of options. Currently, the only supported keys are
``"manual"`` (defaults to ``False``), ``"manual_name"`` (defaults
to ``"Run Interact"``) and ``"auto_display"`` (defaults to ``False``).
**kwargs : various, optional
An interactive widget is created for each keyword argument that is a
valid widget abbreviation.
Note that the first two parameters intentionally start with a double
underscore to avoid being mixed up with keyword arguments passed by
``**kwargs``.
| class interactive(VBox):
"""
A VBox container containing a group of interactive widgets tied to a
function.
Parameters
----------
__interact_f : function
The function to which the interactive widgets are tied. The `**kwargs`
should match the function signature.
__options : dict
A dict of options. Currently, the only supported keys are
``"manual"`` (defaults to ``False``), ``"manual_name"`` (defaults
to ``"Run Interact"``) and ``"auto_display"`` (defaults to ``False``).
**kwargs : various, optional
An interactive widget is created for each keyword argument that is a
valid widget abbreviation.
Note that the first two parameters intentionally start with a double
underscore to avoid being mixed up with keyword arguments passed by
``**kwargs``.
"""
def __init__(self, __interact_f, __options={}, **kwargs):
VBox.__init__(self, _dom_classes=['widget-interact'])
self.result = None
self.args = []
self.kwargs = {}
self.f = f = __interact_f
self.clear_output = kwargs.pop('clear_output', True)
self.manual = __options.get("manual", False)
self.manual_name = __options.get("manual_name", "Run Interact")
self.auto_display = __options.get("auto_display", False)
new_kwargs = self.find_abbreviations(kwargs)
# Before we proceed, let's make sure that the user has passed a set of args+kwargs
# that will lead to a valid call of the function. This protects against unspecified
# and doubly-specified arguments.
try:
check_argspec(f)
except TypeError:
# if we can't inspect, we can't validate
pass
else:
getcallargs(f, **{n:v for n,v,_ in new_kwargs})
# Now build the widgets from the abbreviations.
self.kwargs_widgets = self.widgets_from_abbreviations(new_kwargs)
# This has to be done as an assignment, not using self.children.append,
# so that traitlets notices the update. We skip any objects (such as fixed) that
# are not DOMWidgets.
c = [w for w in self.kwargs_widgets if isinstance(w, DOMWidget)]
# If we are only to run the function on demand, add a button to request this.
if self.manual:
self.manual_button = Button(description=self.manual_name)
c.append(self.manual_button)
self.out = Output()
c.append(self.out)
self.children = c
# Wire up the widgets
# If we are doing manual running, the callback is only triggered by the button
# Otherwise, it is triggered for every trait change received
# On-demand running also suppresses running the function with the initial parameters
if self.manual:
self.manual_button.on_click(self.update)
# Also register input handlers on text areas, so the user can hit return to
# invoke execution.
for w in self.kwargs_widgets:
if isinstance(w, Text):
w.continuous_update = False
w.observe(self.update, names='value')
else:
for widget in self.kwargs_widgets:
widget.observe(self.update, names='value')
self.update()
# Callback function
def update(self, *args):
"""
Call the interact function and update the output widget with
the result of the function call.
Parameters
----------
*args : ignored
Required for this method to be used as traitlets callback.
"""
self.kwargs = {}
if self.manual:
self.manual_button.disabled = True
try:
show_inline_matplotlib_plots()
with self.out:
if self.clear_output:
clear_output(wait=True)
for widget in self.kwargs_widgets:
value = widget.get_interact_value()
self.kwargs[widget._kwarg] = value
self.result = self.f(**self.kwargs)
show_inline_matplotlib_plots()
if self.auto_display and self.result is not None:
display(self.result)
except Exception as e:
ip = get_ipython()
if ip is None:
self.log.warning("Exception in interact callback: %s", e, exc_info=True)
else:
ip.showtraceback()
finally:
if self.manual:
self.manual_button.disabled = False
# Find abbreviations
def signature(self):
return signature(self.f)
def find_abbreviations(self, kwargs):
"""Find the abbreviations for the given function and kwargs.
Return (name, abbrev, default) tuples.
"""
new_kwargs = []
try:
sig = self.signature()
except (ValueError, TypeError):
# can't inspect, no info from function; only use kwargs
return [ (key, value, value) for key, value in kwargs.items() ]
for param in sig.parameters.values():
for name, value, default in _yield_abbreviations_for_parameter(param, kwargs):
if value is empty:
raise ValueError('cannot find widget or abbreviation for argument: {!r}'.format(name))
new_kwargs.append((name, value, default))
return new_kwargs
# Abbreviations to widgets
def widgets_from_abbreviations(self, seq):
"""Given a sequence of (name, abbrev, default) tuples, return a sequence of Widgets."""
result = []
for name, abbrev, default in seq:
if isinstance(abbrev, Widget) and (not isinstance(abbrev, ValueWidget)):
raise TypeError("{!r} is not a ValueWidget".format(abbrev))
widget = self.widget_from_abbrev(abbrev, default)
if widget is None:
raise ValueError("{!r} cannot be transformed to a widget".format(abbrev))
if not hasattr(widget, "description") or not widget.description:
widget.description = name
widget._kwarg = name
result.append(widget)
return result
@classmethod
def widget_from_abbrev(cls, abbrev, default=empty):
"""Build a ValueWidget instance given an abbreviation or Widget."""
if isinstance(abbrev, ValueWidget) or isinstance(abbrev, fixed):
return abbrev
if isinstance(abbrev, tuple):
widget = cls.widget_from_tuple(abbrev)
if default is not empty:
try:
widget.value = default
except Exception:
# ignore failure to set default
pass
return widget
# Try single value
widget = cls.widget_from_single_value(abbrev)
if widget is not None:
return widget
# Something iterable (list, dict, generator, ...). Note that str and
# tuple should be handled before, that is why we check this case last.
if isinstance(abbrev, Iterable):
widget = cls.widget_from_iterable(abbrev)
if default is not empty:
try:
widget.value = default
except Exception:
# ignore failure to set default
pass
return widget
# No idea...
return None
@staticmethod
def widget_from_single_value(o):
"""Make widgets from single values, which can be used as parameter defaults."""
if isinstance(o, str):
return Text(value=str(o))
elif isinstance(o, bool):
return Checkbox(value=o)
elif isinstance(o, Integral):
min, max, value = _get_min_max_value(None, None, o)
return IntSlider(value=o, min=min, max=max)
elif isinstance(o, Real):
min, max, value = _get_min_max_value(None, None, o)
return FloatSlider(value=o, min=min, max=max)
else:
return None
@staticmethod
def widget_from_tuple(o):
"""Make widgets from a tuple abbreviation."""
if _matches(o, (Real, Real)):
min, max, value = _get_min_max_value(o[0], o[1])
if all(isinstance(_, Integral) for _ in o):
cls = IntSlider
else:
cls = FloatSlider
return cls(value=value, min=min, max=max)
elif _matches(o, (Real, Real, Real)):
step = o[2]
if step <= 0:
raise ValueError("step must be >= 0, not %r" % step)
min, max, value = _get_min_max_value(o[0], o[1], step=step)
if all(isinstance(_, Integral) for _ in o):
cls = IntSlider
else:
cls = FloatSlider
return cls(value=value, min=min, max=max, step=step)
@staticmethod
def widget_from_iterable(o):
"""Make widgets from an iterable. This should not be done for
a string or tuple."""
# Dropdown expects a dict or list, so we convert an arbitrary
# iterable to either of those.
if isinstance(o, (list, dict)):
return Dropdown(options=o)
elif isinstance(o, Mapping):
return Dropdown(options=list(o.items()))
else:
return Dropdown(options=list(o))
# Return a factory for interactive functions
@classmethod
def factory(cls):
options = dict(manual=False, auto_display=True, manual_name="Run Interact")
return _InteractFactory(cls, options)
| (_interactive__interact_f, _interactive__options={}, **kwargs) |
15,832 | ipywidgets.widgets.interaction | __init__ | null | def __init__(self, __interact_f, __options={}, **kwargs):
VBox.__init__(self, _dom_classes=['widget-interact'])
self.result = None
self.args = []
self.kwargs = {}
self.f = f = __interact_f
self.clear_output = kwargs.pop('clear_output', True)
self.manual = __options.get("manual", False)
self.manual_name = __options.get("manual_name", "Run Interact")
self.auto_display = __options.get("auto_display", False)
new_kwargs = self.find_abbreviations(kwargs)
# Before we proceed, let's make sure that the user has passed a set of args+kwargs
# that will lead to a valid call of the function. This protects against unspecified
# and doubly-specified arguments.
try:
check_argspec(f)
except TypeError:
# if we can't inspect, we can't validate
pass
else:
getcallargs(f, **{n:v for n,v,_ in new_kwargs})
# Now build the widgets from the abbreviations.
self.kwargs_widgets = self.widgets_from_abbreviations(new_kwargs)
# This has to be done as an assignment, not using self.children.append,
# so that traitlets notices the update. We skip any objects (such as fixed) that
# are not DOMWidgets.
c = [w for w in self.kwargs_widgets if isinstance(w, DOMWidget)]
# If we are only to run the function on demand, add a button to request this.
if self.manual:
self.manual_button = Button(description=self.manual_name)
c.append(self.manual_button)
self.out = Output()
c.append(self.out)
self.children = c
# Wire up the widgets
# If we are doing manual running, the callback is only triggered by the button
# Otherwise, it is triggered for every trait change received
# On-demand running also suppresses running the function with the initial parameters
if self.manual:
self.manual_button.on_click(self.update)
# Also register input handlers on text areas, so the user can hit return to
# invoke execution.
for w in self.kwargs_widgets:
if isinstance(w, Text):
w.continuous_update = False
w.observe(self.update, names='value')
else:
for widget in self.kwargs_widgets:
widget.observe(self.update, names='value')
self.update()
| (self, _interactive__interact_f, _interactive__options={}, **kwargs) |
15,860 | ipywidgets.widgets.interaction | find_abbreviations | Find the abbreviations for the given function and kwargs.
Return (name, abbrev, default) tuples.
| def find_abbreviations(self, kwargs):
"""Find the abbreviations for the given function and kwargs.
Return (name, abbrev, default) tuples.
"""
new_kwargs = []
try:
sig = self.signature()
except (ValueError, TypeError):
# can't inspect, no info from function; only use kwargs
return [ (key, value, value) for key, value in kwargs.items() ]
for param in sig.parameters.values():
for name, value, default in _yield_abbreviations_for_parameter(param, kwargs):
if value is empty:
raise ValueError('cannot find widget or abbreviation for argument: {!r}'.format(name))
new_kwargs.append((name, value, default))
return new_kwargs
| (self, kwargs) |
15,881 | ipywidgets.widgets.interaction | signature | null | def signature(self):
return signature(self.f)
| (self) |
15,890 | ipywidgets.widgets.interaction | update |
Call the interact function and update the output widget with
the result of the function call.
Parameters
----------
*args : ignored
Required for this method to be used as traitlets callback.
| def update(self, *args):
"""
Call the interact function and update the output widget with
the result of the function call.
Parameters
----------
*args : ignored
Required for this method to be used as traitlets callback.
"""
self.kwargs = {}
if self.manual:
self.manual_button.disabled = True
try:
show_inline_matplotlib_plots()
with self.out:
if self.clear_output:
clear_output(wait=True)
for widget in self.kwargs_widgets:
value = widget.get_interact_value()
self.kwargs[widget._kwarg] = value
self.result = self.f(**self.kwargs)
show_inline_matplotlib_plots()
if self.auto_display and self.result is not None:
display(self.result)
except Exception as e:
ip = get_ipython()
if ip is None:
self.log.warning("Exception in interact callback: %s", e, exc_info=True)
else:
ip.showtraceback()
finally:
if self.manual:
self.manual_button.disabled = False
| (self, *args) |
15,891 | ipywidgets.widgets.interaction | widget_from_iterable | Make widgets from an iterable. This should not be done for
a string or tuple. | @staticmethod
def widget_from_iterable(o):
"""Make widgets from an iterable. This should not be done for
a string or tuple."""
# Dropdown expects a dict or list, so we convert an arbitrary
# iterable to either of those.
if isinstance(o, (list, dict)):
return Dropdown(options=o)
elif isinstance(o, Mapping):
return Dropdown(options=list(o.items()))
else:
return Dropdown(options=list(o))
| (o) |
15,892 | ipywidgets.widgets.interaction | widget_from_single_value | Make widgets from single values, which can be used as parameter defaults. | @staticmethod
def widget_from_single_value(o):
"""Make widgets from single values, which can be used as parameter defaults."""
if isinstance(o, str):
return Text(value=str(o))
elif isinstance(o, bool):
return Checkbox(value=o)
elif isinstance(o, Integral):
min, max, value = _get_min_max_value(None, None, o)
return IntSlider(value=o, min=min, max=max)
elif isinstance(o, Real):
min, max, value = _get_min_max_value(None, None, o)
return FloatSlider(value=o, min=min, max=max)
else:
return None
| (o) |
15,893 | ipywidgets.widgets.interaction | widget_from_tuple | Make widgets from a tuple abbreviation. | @staticmethod
def widget_from_tuple(o):
"""Make widgets from a tuple abbreviation."""
if _matches(o, (Real, Real)):
min, max, value = _get_min_max_value(o[0], o[1])
if all(isinstance(_, Integral) for _ in o):
cls = IntSlider
else:
cls = FloatSlider
return cls(value=value, min=min, max=max)
elif _matches(o, (Real, Real, Real)):
step = o[2]
if step <= 0:
raise ValueError("step must be >= 0, not %r" % step)
min, max, value = _get_min_max_value(o[0], o[1], step=step)
if all(isinstance(_, Integral) for _ in o):
cls = IntSlider
else:
cls = FloatSlider
return cls(value=value, min=min, max=max, step=step)
| (o) |
15,894 | ipywidgets.widgets.interaction | widgets_from_abbreviations | Given a sequence of (name, abbrev, default) tuples, return a sequence of Widgets. | def widgets_from_abbreviations(self, seq):
"""Given a sequence of (name, abbrev, default) tuples, return a sequence of Widgets."""
result = []
for name, abbrev, default in seq:
if isinstance(abbrev, Widget) and (not isinstance(abbrev, ValueWidget)):
raise TypeError("{!r} is not a ValueWidget".format(abbrev))
widget = self.widget_from_abbrev(abbrev, default)
if widget is None:
raise ValueError("{!r} cannot be transformed to a widget".format(abbrev))
if not hasattr(widget, "description") or not widget.description:
widget.description = name
widget._kwarg = name
result.append(widget)
return result
| (self, seq) |
15,897 | traitlets.traitlets | link | Link traits from different objects together so they remain in sync.
Parameters
----------
source : (object / attribute name) pair
target : (object / attribute name) pair
transform: iterable with two callables (optional)
Data transformation between source and target and target and source.
Examples
--------
>>> class X(HasTraits):
... value = Int()
>>> src = X(value=1)
>>> tgt = X(value=42)
>>> c = link((src, "value"), (tgt, "value"))
Setting source updates target objects:
>>> src.value = 5
>>> tgt.value
5
| class link:
"""Link traits from different objects together so they remain in sync.
Parameters
----------
source : (object / attribute name) pair
target : (object / attribute name) pair
transform: iterable with two callables (optional)
Data transformation between source and target and target and source.
Examples
--------
>>> class X(HasTraits):
... value = Int()
>>> src = X(value=1)
>>> tgt = X(value=42)
>>> c = link((src, "value"), (tgt, "value"))
Setting source updates target objects:
>>> src.value = 5
>>> tgt.value
5
"""
updating = False
def __init__(self, source: t.Any, target: t.Any, transform: t.Any = None) -> None:
_validate_link(source, target)
self.source, self.target = source, target
self._transform, self._transform_inv = transform if transform else (lambda x: x,) * 2
self.link()
def link(self) -> None:
try:
setattr(
self.target[0],
self.target[1],
self._transform(getattr(self.source[0], self.source[1])),
)
finally:
self.source[0].observe(self._update_target, names=self.source[1])
self.target[0].observe(self._update_source, names=self.target[1])
@contextlib.contextmanager
def _busy_updating(self) -> t.Any:
self.updating = True
try:
yield
finally:
self.updating = False
def _update_target(self, change: t.Any) -> None:
if self.updating:
return
with self._busy_updating():
setattr(self.target[0], self.target[1], self._transform(change.new))
if getattr(self.source[0], self.source[1]) != change.new:
raise TraitError(
f"Broken link {self}: the source value changed while updating " "the target."
)
def _update_source(self, change: t.Any) -> None:
if self.updating:
return
with self._busy_updating():
setattr(self.source[0], self.source[1], self._transform_inv(change.new))
if getattr(self.target[0], self.target[1]) != change.new:
raise TraitError(
f"Broken link {self}: the target value changed while updating " "the source."
)
def unlink(self) -> None:
self.source[0].unobserve(self._update_target, names=self.source[1])
self.target[0].unobserve(self._update_source, names=self.target[1])
| (source: 't.Any', target: 't.Any', transform: 't.Any' = None) -> 'None' |
15,898 | traitlets.traitlets | __init__ | null | def __init__(self, source: t.Any, target: t.Any, transform: t.Any = None) -> None:
_validate_link(source, target)
self.source, self.target = source, target
self._transform, self._transform_inv = transform if transform else (lambda x: x,) * 2
self.link()
| (self, source: Any, target: Any, transform: Optional[Any] = None) -> NoneType |
15,899 | traitlets.traitlets | _busy_updating | null | def _validate_link(*tuples: t.Any) -> None:
"""Validate arguments for traitlet link functions"""
for tup in tuples:
if not len(tup) == 2:
raise TypeError(
"Each linked traitlet must be specified as (HasTraits, 'trait_name'), not %r" % t
)
obj, trait_name = tup
if not isinstance(obj, HasTraits):
raise TypeError("Each object must be HasTraits, not %r" % type(obj))
if trait_name not in obj.traits():
raise TypeError(f"{obj!r} has no trait {trait_name!r}")
| (self) -> Any |
15,900 | traitlets.traitlets | _update_source | null | def _update_source(self, change: t.Any) -> None:
if self.updating:
return
with self._busy_updating():
setattr(self.source[0], self.source[1], self._transform_inv(change.new))
if getattr(self.target[0], self.target[1]) != change.new:
raise TraitError(
f"Broken link {self}: the target value changed while updating " "the source."
)
| (self, change: Any) -> NoneType |
15,901 | traitlets.traitlets | _update_target | null | def _update_target(self, change: t.Any) -> None:
if self.updating:
return
with self._busy_updating():
setattr(self.target[0], self.target[1], self._transform(change.new))
if getattr(self.source[0], self.source[1]) != change.new:
raise TraitError(
f"Broken link {self}: the source value changed while updating " "the target."
)
| (self, change: Any) -> NoneType |
15,902 | traitlets.traitlets | link | null | def link(self) -> None:
try:
setattr(
self.target[0],
self.target[1],
self._transform(getattr(self.source[0], self.source[1])),
)
finally:
self.source[0].observe(self._update_target, names=self.source[1])
self.target[0].observe(self._update_source, names=self.target[1])
| (self) -> NoneType |
15,903 | traitlets.traitlets | unlink | null | def unlink(self) -> None:
self.source[0].unobserve(self._update_target, names=self.source[1])
self.target[0].unobserve(self._update_source, names=self.target[1])
| (self) -> NoneType |
15,904 | traitlets.traitlets | observe | A decorator which can be used to observe Traits on a class.
The handler passed to the decorator will be called with one ``change``
dict argument. The change dictionary at least holds a 'type' key and a
'name' key, corresponding respectively to the type of notification and the
name of the attribute that triggered the 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.
Parameters
----------
*names
The str names of the Traits to observe on the object.
type : str, kwarg-only
The type of event to observe (e.g. 'change')
| def observe(*names: Sentinel | str, type: str = "change") -> ObserveHandler:
"""A decorator which can be used to observe Traits on a class.
The handler passed to the decorator will be called with one ``change``
dict argument. The change dictionary at least holds a 'type' key and a
'name' key, corresponding respectively to the type of notification and the
name of the attribute that triggered the 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.
Parameters
----------
*names
The str names of the Traits to observe on the object.
type : str, kwarg-only
The type of event to observe (e.g. 'change')
"""
if not names:
raise TypeError("Please specify at least one trait name to observe.")
for name in names:
if name is not All and not isinstance(name, str):
raise TypeError("trait names to observe must be strings or All, not %r" % name)
return ObserveHandler(names, type=type)
| (*names: traitlets.utils.sentinel.Sentinel | str, type: str = 'change') -> traitlets.traitlets.ObserveHandler |
15,907 | traitlets.traitlets | validate | A decorator to register cross validator of HasTraits object's state
when a Trait is set.
The handler passed to the decorator must have one ``proposal`` dict argument.
The proposal dictionary must hold the following keys:
* ``owner`` : the HasTraits instance
* ``value`` : the proposed value for the modified trait attribute
* ``trait`` : the TraitType instance associated with the attribute
Parameters
----------
*names
The str names of the Traits to validate.
Notes
-----
Since the owner has access to the ``HasTraits`` instance via the 'owner' key,
the registered cross validator could potentially make changes to attributes
of the ``HasTraits`` instance. However, we recommend not to do so. The reason
is that the cross-validation of attributes may run in arbitrary order when
exiting the ``hold_trait_notifications`` context, and such changes may not
commute.
| def validate(*names: Sentinel | str) -> ValidateHandler:
"""A decorator to register cross validator of HasTraits object's state
when a Trait is set.
The handler passed to the decorator must have one ``proposal`` dict argument.
The proposal dictionary must hold the following keys:
* ``owner`` : the HasTraits instance
* ``value`` : the proposed value for the modified trait attribute
* ``trait`` : the TraitType instance associated with the attribute
Parameters
----------
*names
The str names of the Traits to validate.
Notes
-----
Since the owner has access to the ``HasTraits`` instance via the 'owner' key,
the registered cross validator could potentially make changes to attributes
of the ``HasTraits`` instance. However, we recommend not to do so. The reason
is that the cross-validation of attributes may run in arbitrary order when
exiting the ``hold_trait_notifications`` context, and such changes may not
commute.
"""
if not names:
raise TypeError("Please specify at least one trait name to validate.")
for name in names:
if name is not All and not isinstance(name, str):
raise TypeError("trait names to validate must be strings or All, not %r" % name)
return ValidateHandler(names)
| (*names: traitlets.utils.sentinel.Sentinel | str) -> traitlets.traitlets.ValidateHandler |
15,908 | ipyleaflet.leaflet | wait_for_change | null | def wait_for_change(widget, value):
future = asyncio.Future()
def get_value(change):
future.set_result(change.new)
widget.unobserve(get_value, value)
widget.observe(get_value, value)
return future
| (widget, value) |
15,911 | hypothesis.core | given | A decorator for turning a test function that accepts arguments into a
randomized test.
This is the main entry point to Hypothesis.
| def given(
*_given_arguments: Union[SearchStrategy[Any], EllipsisType],
**_given_kwargs: Union[SearchStrategy[Any], EllipsisType],
) -> Callable[
[Callable[..., Optional[Coroutine[Any, Any, None]]]], Callable[..., None]
]:
"""A decorator for turning a test function that accepts arguments into a
randomized test.
This is the main entry point to Hypothesis.
"""
def run_test_as_given(test):
if inspect.isclass(test):
# Provide a meaningful error to users, instead of exceptions from
# internals that assume we're dealing with a function.
raise InvalidArgument("@given cannot be applied to a class.")
given_arguments = tuple(_given_arguments)
given_kwargs = dict(_given_kwargs)
original_sig = get_signature(test)
if given_arguments == (Ellipsis,) and not given_kwargs:
# user indicated that they want to infer all arguments
given_kwargs = {
p.name: Ellipsis
for p in original_sig.parameters.values()
if p.kind in (p.POSITIONAL_OR_KEYWORD, p.KEYWORD_ONLY)
}
given_arguments = ()
check_invalid = is_invalid_test(
test, original_sig, given_arguments, given_kwargs
)
# If the argument check found problems, return a dummy test function
# that will raise an error if it is actually called.
if check_invalid is not None:
return check_invalid
# Because the argument check succeeded, we can convert @given's
# positional arguments into keyword arguments for simplicity.
if given_arguments:
assert not given_kwargs
posargs = [
p.name
for p in original_sig.parameters.values()
if p.kind is p.POSITIONAL_OR_KEYWORD
]
given_kwargs = dict(list(zip(posargs[::-1], given_arguments[::-1]))[::-1])
# These have been converted, so delete them to prevent accidental use.
del given_arguments
new_signature = new_given_signature(original_sig, given_kwargs)
# Use type information to convert "infer" arguments into appropriate strategies.
if ... in given_kwargs.values():
hints = get_type_hints(test)
for name in [name for name, value in given_kwargs.items() if value is ...]:
if name not in hints:
return _invalid(
f"passed {name}=... for {test.__name__}, but {name} has "
"no type annotation",
test=test,
given_kwargs=given_kwargs,
)
given_kwargs[name] = st.from_type(hints[name])
prev_self = Unset = object()
@impersonate(test)
@define_function_signature(test.__name__, test.__doc__, new_signature)
def wrapped_test(*arguments, **kwargs):
# Tell pytest to omit the body of this function from tracebacks
__tracebackhide__ = True
test = wrapped_test.hypothesis.inner_test
if getattr(test, "is_hypothesis_test", False):
raise InvalidArgument(
f"You have applied @given to the test {test.__name__} more than "
"once, which wraps the test several times and is extremely slow. "
"A similar effect can be gained by combining the arguments "
"of the two calls to given. For example, instead of "
"@given(booleans()) @given(integers()), you could write "
"@given(booleans(), integers())"
)
settings = wrapped_test._hypothesis_internal_use_settings
random = get_random_for_wrapped_test(test, wrapped_test)
arguments, kwargs, stuff = process_arguments_to_given(
wrapped_test, arguments, kwargs, given_kwargs, new_signature.parameters
)
if (
inspect.iscoroutinefunction(test)
and get_executor(stuff.selfy) is default_executor
):
# See https://github.com/HypothesisWorks/hypothesis/issues/3054
# If our custom executor doesn't handle coroutines, or we return an
# awaitable from a non-async-def function, we just rely on the
# return_value health check. This catches most user errors though.
raise InvalidArgument(
"Hypothesis doesn't know how to run async test functions like "
f"{test.__name__}. You'll need to write a custom executor, "
"or use a library like pytest-asyncio or pytest-trio which can "
"handle the translation for you.\n See https://hypothesis."
"readthedocs.io/en/latest/details.html#custom-function-execution"
)
runner = stuff.selfy
if isinstance(stuff.selfy, TestCase) and test.__name__ in dir(TestCase):
msg = (
f"You have applied @given to the method {test.__name__}, which is "
"used by the unittest runner but is not itself a test."
" This is not useful in any way."
)
fail_health_check(settings, msg, HealthCheck.not_a_test_method)
if bad_django_TestCase(runner): # pragma: no cover
# Covered by the Django tests, but not the pytest coverage task
raise InvalidArgument(
"You have applied @given to a method on "
f"{type(runner).__qualname__}, but this "
"class does not inherit from the supported versions in "
"`hypothesis.extra.django`. Use the Hypothesis variants "
"to ensure that each example is run in a separate "
"database transaction."
)
if settings.database is not None:
nonlocal prev_self
# Check selfy really is self (not e.g. a mock) before we health-check
cur_self = (
stuff.selfy
if getattr(type(stuff.selfy), test.__name__, None) is wrapped_test
else None
)
if prev_self is Unset:
prev_self = cur_self
elif cur_self is not prev_self:
msg = (
f"The method {test.__qualname__} was called from multiple "
"different executors. This may lead to flaky tests and "
"nonreproducible errors when replaying from database."
)
fail_health_check(settings, msg, HealthCheck.differing_executors)
state = StateForActualGivenExecution(
stuff, test, settings, random, wrapped_test
)
reproduce_failure = wrapped_test._hypothesis_internal_use_reproduce_failure
# If there was a @reproduce_failure decorator, use it to reproduce
# the error (or complain that we couldn't). Either way, this will
# always raise some kind of error.
if reproduce_failure is not None:
expected_version, failure = reproduce_failure
if expected_version != __version__:
raise InvalidArgument(
"Attempting to reproduce a failure from a different "
"version of Hypothesis. This failure is from %s, but "
"you are currently running %r. Please change your "
"Hypothesis version to a matching one."
% (expected_version, __version__)
)
try:
state.execute_once(
ConjectureData.for_buffer(decode_failure(failure)),
print_example=True,
is_final=True,
)
raise DidNotReproduce(
"Expected the test to raise an error, but it "
"completed successfully."
)
except StopTest:
raise DidNotReproduce(
"The shape of the test data has changed in some way "
"from where this blob was defined. Are you sure "
"you're running the same test?"
) from None
except UnsatisfiedAssumption:
raise DidNotReproduce(
"The test data failed to satisfy an assumption in the "
"test. Have you added it since this blob was generated?"
) from None
# There was no @reproduce_failure, so start by running any explicit
# examples from @example decorators.
errors = list(
execute_explicit_examples(
state, wrapped_test, arguments, kwargs, original_sig
)
)
if errors:
# If we're not going to report multiple bugs, we would have
# stopped running explicit examples at the first failure.
assert len(errors) == 1 or state.settings.report_multiple_bugs
# If an explicit example raised a 'skip' exception, ensure it's never
# wrapped up in an exception group. Because we break out of the loop
# immediately on finding a skip, if present it's always the last error.
if isinstance(errors[-1][1], skip_exceptions_to_reraise()):
# Covered by `test_issue_3453_regression`, just in a subprocess.
del errors[:-1] # pragma: no cover
_raise_to_user(errors, state.settings, [], " in explicit examples")
# If there were any explicit examples, they all ran successfully.
# The next step is to use the Conjecture engine to run the test on
# many different inputs.
ran_explicit_examples = Phase.explicit in state.settings.phases and getattr(
wrapped_test, "hypothesis_explicit_examples", ()
)
SKIP_BECAUSE_NO_EXAMPLES = unittest.SkipTest(
"Hypothesis has been told to run no examples for this test."
)
if not (
Phase.reuse in settings.phases or Phase.generate in settings.phases
):
if not ran_explicit_examples:
raise SKIP_BECAUSE_NO_EXAMPLES
return
try:
if isinstance(runner, TestCase) and hasattr(runner, "subTest"):
subTest = runner.subTest
try:
runner.subTest = types.MethodType(fake_subTest, runner)
state.run_engine()
finally:
runner.subTest = subTest
else:
state.run_engine()
except BaseException as e:
# The exception caught here should either be an actual test
# failure (or BaseExceptionGroup), or some kind of fatal error
# that caused the engine to stop.
generated_seed = wrapped_test._hypothesis_internal_use_generated_seed
with local_settings(settings):
if not (state.failed_normally or generated_seed is None):
if running_under_pytest:
report(
f"You can add @seed({generated_seed}) to this test or "
f"run pytest with --hypothesis-seed={generated_seed} "
"to reproduce this failure."
)
else:
report(
f"You can add @seed({generated_seed}) to this test to "
"reproduce this failure."
)
# The dance here is to avoid showing users long tracebacks
# full of Hypothesis internals they don't care about.
# We have to do this inline, to avoid adding another
# internal stack frame just when we've removed the rest.
#
# Using a variable for our trimmed error ensures that the line
# which will actually appear in tracebacks is as clear as
# possible - "raise the_error_hypothesis_found".
the_error_hypothesis_found = e.with_traceback(
None
if isinstance(e, BaseExceptionGroup)
else get_trimmed_traceback()
)
raise the_error_hypothesis_found
if not (ran_explicit_examples or state.ever_executed):
raise SKIP_BECAUSE_NO_EXAMPLES
def _get_fuzz_target() -> (
Callable[[Union[bytes, bytearray, memoryview, BinaryIO]], Optional[bytes]]
):
# Because fuzzing interfaces are very performance-sensitive, we use a
# somewhat more complicated structure here. `_get_fuzz_target()` is
# called by the `HypothesisHandle.fuzz_one_input` property, allowing
# us to defer our collection of the settings, random instance, and
# reassignable `inner_test` (etc) until `fuzz_one_input` is accessed.
#
# We then share the performance cost of setting up `state` between
# many invocations of the target. We explicitly force `deadline=None`
# for performance reasons, saving ~40% the runtime of an empty test.
test = wrapped_test.hypothesis.inner_test
settings = Settings(
parent=wrapped_test._hypothesis_internal_use_settings, deadline=None
)
random = get_random_for_wrapped_test(test, wrapped_test)
_args, _kwargs, stuff = process_arguments_to_given(
wrapped_test, (), {}, given_kwargs, new_signature.parameters
)
assert not _args
assert not _kwargs
state = StateForActualGivenExecution(
stuff, test, settings, random, wrapped_test
)
digest = function_digest(test)
# We track the minimal-so-far example for each distinct origin, so
# that we track log-n instead of n examples for long runs. In particular
# it means that we saturate for common errors in long runs instead of
# storing huge volumes of low-value data.
minimal_failures: dict = {}
def fuzz_one_input(
buffer: Union[bytes, bytearray, memoryview, BinaryIO]
) -> Optional[bytes]:
# This inner part is all that the fuzzer will actually run,
# so we keep it as small and as fast as possible.
if isinstance(buffer, io.IOBase):
buffer = buffer.read(BUFFER_SIZE)
assert isinstance(buffer, (bytes, bytearray, memoryview))
data = ConjectureData.for_buffer(buffer)
try:
state.execute_once(data)
except (StopTest, UnsatisfiedAssumption):
return None
except BaseException:
buffer = bytes(data.buffer)
known = minimal_failures.get(data.interesting_origin)
if settings.database is not None and (
known is None or sort_key(buffer) <= sort_key(known)
):
settings.database.save(digest, buffer)
minimal_failures[data.interesting_origin] = buffer
raise
return bytes(data.buffer)
fuzz_one_input.__doc__ = HypothesisHandle.fuzz_one_input.__doc__
return fuzz_one_input
# After having created the decorated test function, we need to copy
# over some attributes to make the switch as seamless as possible.
for attrib in dir(test):
if not (attrib.startswith("_") or hasattr(wrapped_test, attrib)):
setattr(wrapped_test, attrib, getattr(test, attrib))
wrapped_test.is_hypothesis_test = True
if hasattr(test, "_hypothesis_internal_settings_applied"):
# Used to check if @settings is applied twice.
wrapped_test._hypothesis_internal_settings_applied = True
wrapped_test._hypothesis_internal_use_seed = getattr(
test, "_hypothesis_internal_use_seed", None
)
wrapped_test._hypothesis_internal_use_settings = (
getattr(test, "_hypothesis_internal_use_settings", None) or Settings.default
)
wrapped_test._hypothesis_internal_use_reproduce_failure = getattr(
test, "_hypothesis_internal_use_reproduce_failure", None
)
wrapped_test.hypothesis = HypothesisHandle(test, _get_fuzz_target, given_kwargs)
return wrapped_test
return run_test_as_given
| (*_given_arguments: Union[hypothesis.strategies.SearchStrategy[Any], ellipsis], **_given_kwargs: Union[hypothesis.strategies.SearchStrategy[Any], ellipsis]) -> Callable[[Callable[..., Optional[Coroutine[Any, Any, NoneType]]]], Callable[..., NoneType]] |
15,912 | d8s_hypothesis.hypothesis_wrapper | hypothesis_get_strategy_results | Return the given n of results from the given hypothesis strategy.
For a list of hypothesis strategies, see: https://hypothesis.readthedocs.io/en/latest/data.html.
| def hypothesis_get_strategy_results(strategy, *args, n: int = 10, **kwargs):
"""Return the given n of results from the given hypothesis strategy.
For a list of hypothesis strategies, see: https://hypothesis.readthedocs.io/en/latest/data.html.
"""
class A: # pylint: disable=R0903
def __init__(self):
self.l = [] # noqa:E741
@given(strategy(*args))
@settings(max_examples=n, **kwargs)
def a(self, value):
"""."""
self.l.append(value)
obj = A()
obj.a() # pylint: disable=E1120
return obj.l
| (strategy, *args, n: int = 10, **kwargs) |
15,914 | hypothesis | settings | A settings object configures options including verbosity, runtime controls,
persistence, determinism, and more.
Default values are picked up from the settings.default object and
changes made there will be picked up in newly created settings.
| from hypothesis import settings
| (parent: Optional[ForwardRef('settings')] = None, *, max_examples: int = not_set, derandomize: bool = not_set, database: Optional[ForwardRef('ExampleDatabase')] = not_set, verbosity: 'Verbosity' = not_set, phases: Collection[ForwardRef('Phase')] = not_set, stateful_step_count: int = not_set, report_multiple_bugs: bool = not_set, suppress_health_check: Collection[ForwardRef('HealthCheck')] = not_set, deadline: Union[int, float, datetime.timedelta, NoneType] = not_set, print_blob: bool = not_set, backend: str = not_set) -> None |
15,915 | hypothesis._settings | __call__ | Make the settings object (self) an attribute of the test.
The settings are later discovered by looking them up on the test itself.
| def __call__(self, test: T) -> T:
"""Make the settings object (self) an attribute of the test.
The settings are later discovered by looking them up on the test itself.
"""
# Aliasing as Any avoids mypy errors (attr-defined) when accessing and
# setting custom attributes on the decorated function or class.
_test: Any = test
# Using the alias here avoids a mypy error (return-value) later when
# ``test`` is returned, because this check results in type refinement.
if not callable(_test):
raise InvalidArgument(
"settings objects can be called as a decorator with @given, "
f"but decorated {test=} is not callable."
)
if inspect.isclass(test):
from hypothesis.stateful import RuleBasedStateMachine
if issubclass(_test, RuleBasedStateMachine):
attr_name = "_hypothesis_internal_settings_applied"
if getattr(test, attr_name, False):
raise InvalidArgument(
"Applying the @settings decorator twice would "
"overwrite the first version; merge their arguments "
"instead."
)
setattr(test, attr_name, True)
_test.TestCase.settings = self
return test # type: ignore
else:
raise InvalidArgument(
"@settings(...) can only be used as a decorator on "
"functions, or on subclasses of RuleBasedStateMachine."
)
if hasattr(_test, "_hypothesis_internal_settings_applied"):
# Can't use _hypothesis_internal_use_settings as an indicator that
# @settings was applied, because @given also assigns that attribute.
descr = get_pretty_function_description(test)
raise InvalidArgument(
f"{descr} has already been decorated with a settings object.\n"
f" Previous: {_test._hypothesis_internal_use_settings!r}\n"
f" This: {self!r}"
)
_test._hypothesis_internal_use_settings = self
_test._hypothesis_internal_settings_applied = True
return test
| (self, test: ~T) -> ~T |
15,916 | hypothesis._settings | __getattr__ | null | def __getattr__(self, name):
if name in all_settings:
return all_settings[name].default
else:
raise AttributeError(f"settings has no attribute {name}")
| (self, name) |
15,917 | hypothesis._settings | __init__ | null | def __init__(
self,
parent: Optional["settings"] = None,
*,
# This looks pretty strange, but there's good reason: we want Mypy to detect
# bad calls downstream, but not to freak out about the `= not_set` part even
# though it's not semantically valid to pass that as an argument value.
# The intended use is "like **kwargs, but more tractable for tooling".
max_examples: int = not_set, # type: ignore
derandomize: bool = not_set, # type: ignore
database: Optional["ExampleDatabase"] = not_set, # type: ignore
verbosity: "Verbosity" = not_set, # type: ignore
phases: Collection["Phase"] = not_set, # type: ignore
stateful_step_count: int = not_set, # type: ignore
report_multiple_bugs: bool = not_set, # type: ignore
suppress_health_check: Collection["HealthCheck"] = not_set, # type: ignore
deadline: Union[int, float, datetime.timedelta, None] = not_set, # type: ignore
print_blob: bool = not_set, # type: ignore
backend: str = not_set, # type: ignore
) -> None:
if parent is not None:
check_type(settings, parent, "parent")
if derandomize not in (not_set, False):
if database not in (not_set, None): # type: ignore
raise InvalidArgument(
"derandomize=True implies database=None, so passing "
f"{database=} too is invalid."
)
database = None
defaults = parent or settings.default
if defaults is not None:
for setting in all_settings.values():
value = locals()[setting.name]
if value is not_set:
object.__setattr__(
self, setting.name, getattr(defaults, setting.name)
)
else:
object.__setattr__(self, setting.name, setting.validator(value))
| (self, parent: Optional[ForwardRef('settings')] = None, *, max_examples: int = not_set, derandomize: bool = not_set, database: Optional[ForwardRef('ExampleDatabase')] = not_set, verbosity: 'Verbosity' = not_set, phases: Collection[ForwardRef('Phase')] = not_set, stateful_step_count: int = not_set, report_multiple_bugs: bool = not_set, suppress_health_check: Collection[ForwardRef('HealthCheck')] = not_set, deadline: Union[int, float, datetime.timedelta, NoneType] = not_set, print_blob: bool = not_set, backend: str = not_set) -> None |
15,918 | hypothesis._settings | __repr__ | null | def __repr__(self):
from hypothesis.internal.conjecture.data import AVAILABLE_PROVIDERS
bits = sorted(
f"{name}={getattr(self, name)!r}"
for name in all_settings
if (name != "backend" or len(AVAILABLE_PROVIDERS) > 1) # experimental
)
return "settings({})".format(", ".join(bits))
| (self) |
15,919 | hypothesis._settings | __setattr__ | null | def __setattr__(self, name, value):
raise AttributeError("settings objects are immutable")
| (self, name, value) |
15,920 | hypothesis._settings | get_profile | Return the profile with the given name. | @staticmethod
def get_profile(name: str) -> "settings":
"""Return the profile with the given name."""
check_type(str, name, "name")
try:
return settings._profiles[name]
except KeyError:
raise InvalidArgument(f"Profile {name!r} is not registered") from None
| (name: str) -> hypothesis.settings |
15,921 | hypothesis._settings | load_profile | Loads in the settings defined in the profile provided.
If the profile does not exist, InvalidArgument will be raised.
Any setting not defined in the profile will be the library
defined default for that setting.
| @staticmethod
def load_profile(name: str) -> None:
"""Loads in the settings defined in the profile provided.
If the profile does not exist, InvalidArgument will be raised.
Any setting not defined in the profile will be the library
defined default for that setting.
"""
check_type(str, name, "name")
settings._current_profile = name
settings._assign_default_internal(settings.get_profile(name))
| (name: str) -> NoneType |
15,922 | hypothesis._settings | register_profile | Registers a collection of values to be used as a settings profile.
Settings profiles can be loaded by name - for example, you might
create a 'fast' profile which runs fewer examples, keep the 'default'
profile, and create a 'ci' profile that increases the number of
examples and uses a different database to store failures.
The arguments to this method are exactly as for
:class:`~hypothesis.settings`: optional ``parent`` settings, and
keyword arguments for each setting that will be set differently to
parent (or settings.default, if parent is None).
| @staticmethod
def register_profile(
name: str,
parent: Optional["settings"] = None,
**kwargs: Any,
) -> None:
"""Registers a collection of values to be used as a settings profile.
Settings profiles can be loaded by name - for example, you might
create a 'fast' profile which runs fewer examples, keep the 'default'
profile, and create a 'ci' profile that increases the number of
examples and uses a different database to store failures.
The arguments to this method are exactly as for
:class:`~hypothesis.settings`: optional ``parent`` settings, and
keyword arguments for each setting that will be set differently to
parent (or settings.default, if parent is None).
"""
check_type(str, name, "name")
settings._profiles[name] = settings(parent=parent, **kwargs)
| (name: str, parent: Optional[hypothesis.settings] = None, **kwargs: Any) -> NoneType |
15,923 | hypothesis._settings | show_changed | null | def show_changed(self):
bits = []
for name, setting in all_settings.items():
value = getattr(self, name)
if value != setting.default:
bits.append(f"{name}={value!r}")
return ", ".join(sorted(bits, key=len))
| (self) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.