#-----------------------------------------------------------------------------# Copyright (c) Anaconda, Inc., and Bokeh Contributors.# All rights reserved.## The full license is in the file LICENSE.txt, distributed with this software.#-----------------------------------------------------------------------------''' Common enumerations to be used together with |Enum| property.This module provides many pre-defined enumerations, as well as functionsfor creating new enumerations.New enumerations can be created using the |enumeration| function:.. code-block:: python #: Specify a nautically named side, port or starboard MyEnum = enumeration("port", "starboard")Typically, enumerations are used to define |Enum| properties:.. code-block:: python from bokeh.model import Model from bokeh.core.properties import Enum class MyModel(Model): location = Enum(MyEnum, help=""" Whether the thing should be a port or starboard. """)Enumerations have a defined order and support iteration:.. code-block:: python >>> for loc in MyEnum: ... print(loc) ... port starboardas well as containment tests:.. code-block:: python >>> "port" in MyEnum TrueEnumerations can be easily documented in Sphinx documentation with the:ref:`bokeh.sphinxext.bokeh_enum` Sphinx extension.----.. autofunction:: bokeh.core.enums.enumeration----.. |Enum| replace:: :class:`~bokeh.core.properties.Enum`.. |enumeration| replace:: :func:`~bokeh.core.enums.enumeration`'''#-----------------------------------------------------------------------------# Boilerplate#-----------------------------------------------------------------------------from__future__importannotationsimportlogging# isort:skiplog=logging.getLogger(__name__)#-----------------------------------------------------------------------------# Imports#-----------------------------------------------------------------------------# Standard library importsfromtypingimport(Any,Iterator,Literal,get_args,)# Bokeh importsfrom..importcolors,palettesfrom..util.stringsimportnice_join#-----------------------------------------------------------------------------# Globals and constants#-----------------------------------------------------------------------------__all__=('Align','AlternationPolicy','Anchor','AngleUnits','AutosizeMode','ButtonType','CalendarPosition','ContextWhich','CoordinateUnits','DashPattern','DateFormat','DatetimeUnits','Dimension','Dimensions','Direction','FlowMode','FontStyle','HAlign','HatchPattern','HatchPatternAbbreviation','HoldPolicy','HorizontalLocation','ImageOrigin','JitterRandomDistribution','KeyModifier','LabelOrientation','LatLon','LegendClickPolicy','LegendLocation','LineCap','LineDash','LineJoin','Location','MapType','MarkerType','Movable','NamedColor','NumeralLanguage','Orientation','OutputBackend','PaddingUnits','Palette','Place','RegionSelectionMode','RenderLevel','ResetPolicy','Resizable','ResolutionType','RoundingFunction','ScrollbarPolicy','SelectionMode','SizingMode','SizingPolicy','SortDirection','SpatialUnits','StartEnd','StepMode','TextAlign','TextBaseline','TextureRepetition','ToolIcon','TooltipAttachment','TooltipFieldFormatter','TrackPolicy','VAlign','VerticalAlign','VerticalLocation',)#-----------------------------------------------------------------------------# General API#-----------------------------------------------------------------------------#-----------------------------------------------------------------------------# Dev API#-----------------------------------------------------------------------------classEnumeration:''' Represent an enumerated collection of values. .. note:: Instances of ``Enumeration`` typically should not be constructed directly. Instead, use the |enumeration| function. '''__slots__=()_values:list[str]_default:str_case_sensitive:bool_quote:booldef__iter__(self)->Iterator[str]:returniter(self._values)def__contains__(self,value:str)->bool:ifnotself._case_sensitive:value=value.lower()returnvalueinself._valuesdef__str__(self)->str:fn=reprifself._quoteelsestrreturnf"Enumeration({', '.join(fn(x)forxinself._values)})"def__len__(self)->int:returnlen(self._values)__repr__=__str__
[docs]defenumeration(*values:Any,case_sensitive:bool=True,quote:bool=False)->Enumeration:''' Create an |Enumeration| object from a sequence of values. Call ``enumeration`` with a sequence of (unique) strings to create an Enumeration object: .. code-block:: python #: Specify the horizontal alignment for rendering text TextAlign = enumeration("left", "right", "center") Args: values (str) : string enumeration values, passed as positional arguments The order of arguments is the order of the enumeration, and the first element will be considered the default value when used to create |Enum| properties. Keyword Args: case_sensitive (bool, optional) : Whether validation should consider case or not (default: True) quote (bool, optional): Whether values should be quoted in the string representations (default: False) Raises: ValueError if values empty, if any value is not a string or not unique Returns: Enumeration '''iflen(values)==1andhasattr(values[0],"__args__"):values=get_args(values[0])ifnot(valuesandall(isinstance(value,str)andvalueforvalueinvalues)):raiseValueError(f"expected a non-empty sequence of strings, got {nice_join(values)}")iflen(values)!=len(set(values)):raiseValueError(f"enumeration items must be unique, got {nice_join(values)}")attrs:dict[str,Any]={value:valueforvalueinvalues}attrs.update({"_values":list(values),"_default":values[0],"_case_sensitive":case_sensitive,"_quote":quote,})returntype("Enumeration",(Enumeration,),attrs)()
#: Alignment (vertical or horizontal) of a child itemAlign=enumeration("start","center","end")#: Horizontal alignment of a child itemHAlign=enumeration("top","center","bottom")#: Vertical alignment of a child itemVAlign=enumeration("left","center","right")#: Specify to which items apply styling in a container (e.g. in a legend)AlternationPolicy=enumeration("none","even","odd","every")#: Specify an anchor position on a box/frameAnchor=enumeration("top_left","top_center","top_right","center_left","center_center","center_right","bottom_left","bottom_center","bottom_right","top","left","center","right","bottom",)#: Specify the units for an angle valueAngleUnits=enumeration("deg","rad","grad","turn")#: Specify autosize mode for DataTableAutosizeMode=enumeration("fit_columns","fit_viewport","force_fit","none")#: Specify a style for button widgetsButtonType=enumeration("default","primary","success","warning","danger","light")#: Specify a position for the DatePicker calendar to displayCalendarPosition=enumeration("auto","above","below")#: Specify which tick to add additional context toContextWhich=enumeration("start","center","end","all")#: Specify units for mapping coordinatesCoordinateUnits=enumeration("canvas","screen","data")#: Specify a named dashing patter for stroking linesDashPattern=enumeration("solid","dashed","dotted","dotdash","dashdot")#: Specify a format for printing datesDateFormat=enumeration("ATOM","W3C","RFC-3339","ISO-8601","COOKIE","RFC-822","RFC-850","RFC-1036","RFC-1123","RFC-2822","RSS","TIMESTAMP")#: Specify a date/time scaleDatetimeUnits=enumeration("microseconds","milliseconds","seconds","minsec","minutes","hourmin","hours","days","months","years")#: Specify a vertical/horizontal dimensionDimension=enumeration("width","height")#: Specify a vertical/horizontal dimensionsDimensionsType=Literal["width","height","both"]Dimensions=enumeration("width","height","both")#: Specify a stroke direction for circles, wedges, etc.Direction=enumeration("clock","anticlock")#: Specify the flow behavior in CSS layouts.FlowMode=enumeration("block","inline")#: Specify the font style for rendering textFontStyle=enumeration("normal","italic","bold","bold italic")_hatch_patterns=((" ","blank"),(".","dot"),("o","ring"),("-","horizontal_line"),("|","vertical_line"),("+","cross"),('"',"horizontal_dash"),(":","vertical_dash"),("@","spiral"),("/","right_diagonal_line"),("\\","left_diagonal_line"),("x","diagonal_cross"),(",","right_diagonal_dash"),("`","left_diagonal_dash"),("v","horizontal_wave"),(">","vertical_wave"),("*","criss_cross"),)#: Specify one of the built-in patterns for hatching fillsHatchPattern=enumeration(*list(zip(*_hatch_patterns))[1])#: Specify one of the built-in patterns for hatching fills with a one-letter abbreviation#:#: The abbreviations are mapped as follows:#:#: .. code-block:: none#:#: " " : blank#: "." : dot#: "o" : ring#: "-" : horizontal_line#: "|" : vertical_line#: "+" : cross#: '"' : horizontal_dash#: ":" : vertical_dash#: "@" : spiral#: "/" : right_diagonal_line#: "\\" : left_diagonal_line#: "x" : diagonal_cross#: "," : right_diagonal_dash#: "`" : left_diagonal_dash#: "v" : horizontal_wave#: ">" : vertical_wave#: "*" : criss_crossHatchPatternAbbreviation=enumeration(*next(iter(zip(*_hatch_patterns))),quote=True)#: Specify whether events should be combined or collected as-is when a Document hold is in effectHoldPolicyType=Literal["combine","collect"]HoldPolicy=enumeration(HoldPolicyType)#: Specify a horizontal location in plot layoutsHorizontalLocation=enumeration("left","right")#: Defines the coordinate space within an imageImageOrigin=enumeration("bottom_left","top_left","bottom_right","top_right")#: Specify a distribution to use for the Jitter classJitterRandomDistributionType=Literal["uniform","normal"]JitterRandomDistribution=enumeration(JitterRandomDistributionType)#:KeyModifier=Literal["shift","ctrl","alt"]KeyModifier=enumeration("shift","ctrl","alt")#: Specify how labels are oriented with respect to an axisLabelOrientationType=Literal["horizontal","vertical","parallel","normal"]LabelOrientation=enumeration("horizontal","vertical","parallel","normal")#: Specify whether a dimension or coordinate is latitude or longitudeLatLon=enumeration("lat","lon")#: Specify how a legend should respond to click eventsLegendClickPolicy=enumeration("none","hide","mute")#: Specify a fixed location for a Bokeh legendLegendLocation=Anchor#: Specify how stroked lines should be terminatedLineCap=enumeration("butt","round","square")#: Specify a named dash pattern for stroking linesLineDash=enumeration("solid","dashed","dotted","dotdash","dashdot")#: Specify how stroked lines should be joined togetherLineJoin=enumeration("miter","round","bevel")#: Specify a location in plot layoutsLocationType=Literal["above","below","left","right"]Location=enumeration(LocationType)#: Specify a style for a Google mapMapType=enumeration("satellite","roadmap","terrain","hybrid")#: Specify one of the built-in marker typesMarkerType=enumeration("asterisk","circle","circle_cross","circle_dot","circle_x","circle_y","cross","dash","diamond","diamond_cross","diamond_dot","dot","hex","hex_dot","inverted_triangle","plus","square","square_cross","square_dot","square_pin","square_x","star","star_dot","triangle","triangle_dot","triangle_pin","x","y",)#: Indicates in which dimensions an object (a renderer or an UI element) can be moved.Movable=enumeration("none","x","y","both")#: Specify one of the CSS4 named colors (https://www.w3.org/TR/css-color-4/#named-colors)NamedColor=enumeration(*colors.named.__all__,case_sensitive=False)#: Specify a locale for printing numeric valuesNumeralLanguage=enumeration("be-nl","chs","cs","da-dk","de-ch","de","en","en-gb","es-ES","es","et","fi","fr-CA","fr-ch","fr","hu","it","ja","nl-nl","pl","pt-br","pt-pt","ru","ru-UA","sk","th","tr","uk-UA")#: Specify a vertical/horizontal orientation for somethingOrientation=enumeration("horizontal","vertical")#: Specify an output backend to render a plot area ontoOutputBackendType=Literal["canvas","svg","webgl"]OutputBackend=enumeration(OutputBackendType)#: Whether range padding should be interpreted a percentage or and absolute quantityPaddingUnits=enumeration("percent","absolute")#: Specify the name of a palette from :ref:`bokeh.palettes`Palette=enumeration(*palettes.__palettes__)#:PlaceType=Literal["above","below","left","right","center"]Place=enumeration(PlaceType)#: Specify a position in the render order for a Bokeh rendererRenderLevel=enumeration("image","underlay","glyph","guide","annotation","overlay")#: What reset actions should occur on a Plot resetResetPolicy=enumeration("standard","event_only")#: Indicates in which dimensions an object (a renderer or an UI element) can be resized.Resizable=enumeration("none","left","right","top","bottom","x","y","all")#: Specify which resolutions should be used for stripping of leading zerosResolutionType=enumeration("microseconds","milliseconds","seconds","minsec","minutes","hourmin","hours","days","months","years")#: Specify a policy for how numbers should be roundedRoundingFunction=enumeration("round","nearest","floor","rounddown","ceil","roundup")#: Scrollbar policiesScrollbarPolicy=enumeration("auto","visible","hidden")#: Region selection modesRegionSelectionModeType=Literal["replace","append","intersect","subtract","xor"]RegionSelectionMode=enumeration(RegionSelectionModeType)#: Selection modesSelectionModeType=Literal[RegionSelectionModeType,"toggle"]SelectionMode=enumeration(SelectionModeType)#: Sizing mode policiesSizingModeType=Literal["stretch_width","stretch_height","stretch_both","scale_width","scale_height","scale_both","fixed","inherit"]SizingMode=enumeration(SizingModeType)#: Individual sizing mode policiesSizingPolicy=enumeration("fixed","fit","min","max")#: Specify sorting directionsSortDirection=enumeration("ascending","descending")#: Specify units for mapping valuesSpatialUnits=enumeration("screen","data")#: Specify a start/end valueStartEnd=enumeration("start","end")#: Specify a mode for stepwise interpolationStepMode=enumeration("before","after","center")#: Specify the horizontal alignment for rendering textTextAlign=enumeration("left","right","center")#: Specify the baseline location for rendering textTextBaseline=enumeration("top","middle","bottom","alphabetic","hanging","ideographic")#: Specify how textures used as canvas patterns should repeatTextureRepetition=enumeration("repeat","repeat_x","repeat_y","no_repeat")#: Well known tool icon namesToolIcon=enumeration("append_mode","arrow_down_to_bar","arrow_up_from_bar","auto_box_zoom","bold","box_edit","box_select","box_zoom","caret_down","caret_left","caret_right","caret_up","check","chevron_down","chevron_left","chevron_right","chevron_up","clear_selection","copy","crosshair","delete","freehand_draw","fullscreen","help","hover","intersect_mode","invert_selection","italic","lasso_select","line_edit","maximize","minimize","pan","pin","point_draw","pointer","poly_draw","poly_edit","polygon_select","range","redo","replace_mode","reset","save","see_off","see_on","settings","square","square_check","subtract_mode","tap_select","text_align_center","text_align_left","text_align_right","undo","unknown","unpin","wheel_pan","wheel_zoom","x_box_select","x_box_zoom","x_grip","x_pan","xor_mode","y_box_select","y_box_zoom","y_grip","y_pan","zoom_in","zoom_out",)#: Specify an attachment for tooltipsTooltipAttachment=enumeration("horizontal","vertical","left","right","above","below")#: Specify how a format string for a tooltip field should be interpretedTooltipFieldFormatter=enumeration("numeral","datetime","printf")#: Grid track (row/column) sizing policiesTrackPolicy=enumeration("auto","min","max","flex","fixed")#: Specify the vertical alignment for rendering textVerticalAlign=enumeration("top","middle","bottom")#: Specify a vertical location in plot layoutsVerticalLocation=enumeration("above","below")#-----------------------------------------------------------------------------# Private API#-----------------------------------------------------------------------------#-----------------------------------------------------------------------------# Code#-----------------------------------------------------------------------------