Parameter types#
You can get some of the benefit of Param from Parameter and Parameterized alone, such as having constant or readonly parameters, parameter value inheritance, and parameter docstrings. However, you’ll typically want a more specialized Parameter type so that you can enforce type and bounds restrictions and enable suitable behavior specialized for that type of parameter. Param ships with a large set of pre-defined more-specific Parameter types, and additional custom parameters can and should be added for any domain-specific parameter types needed.
The predefined types are organized into a class hierarchy where each type is a subclass of Parameter:
String: String value, optionally constrained by a regular expression
Color: A hex string specifying an RGB color, or a standard named color
Boolean: True or False (or None, if allowed)
Event: True/False parameter used to trigger actions (see Dependencies and watchers).
Dynamic: Base class for values that can be set to a callable that returns a concrete value
Number: Any type of numeric value
Integer: Positive or negative integer value
Magnitude: Positive value in the inclusive range 0.0,1.0
Date: Date or datetime type
CalendarDate: Date (not datetime)
Tuple: Python tuple of a fixed length and optional fixed type
NumericTuple: Python tuple of a fixed length and a numeric type
XYCoordinates: Position in an x,y plane
Range: A numeric range or interval
DateRange: A range of dates or datetimes
CalendarDateRange: A range of dates (not datetimes)
List: A list of objects, potentially of a fixed, min, or max length
HookList: A list of callables, for calling user-defined code at a processing stage
Path: A POSIX-style string specifying the location of a local file or folder
Filename: A POSIX-style string specifying the location of a local file
Foldername: A POSIX-style string specifying the location of a local folder
SelectorBase: Abstract superclass covering various selector parameter types
Selector: One object selected out of a provided ordered list of objects
FileSelector: One filename selected out of those matching a provided glob
ListSelector: Multiple objects selected out of a provided list of objects
MultiFileSelector: Multiple filenames selected out of those matching a provided glob
ClassSelector: An instance or class of a specified Python class or superclass
Callable: A callable object, such as a function.
Action: A callable with no arguments, ready to invoke
Composite: A list of other attributes or parameters of this class, settable and readable as a group
The full behavior of these types is covered in the Reference Manual. Here we will discuss the major categories of Parameter type and how to use them, including examples of what each type does not allow (labeled with param.exceptions_summarized():
). Each of these classes is also suitable for subclassing to create more specialized types enforcing your own specific constraints. After reading about Parameters in general, feel free to skip around in this page and only look at the Parameter types of interest to you!
Strings#
param.String
: String value, with optional regular expression (regex) constraints
A param.String
may be set to any Python string value by default, or it may be constrained to match a provided regular expression regex
. Like all other Parameters, it can optionally also allow_None
, which will be true by default if the default value is None.
import param
class S(param.Parameterized):
s = param.String('Four score', regex='[A-Z][a-z][a-z][a-z ]*')
s = S()
s.s
'Four score'
with param.exceptions_summarized():
s.s = 5
ValueError: String parameter 'S.s' only takes a string value, not value of <class 'int'>.
s.s = 'Forever after'
with param.exceptions_summarized():
s.s = 'four of spades'
ValueError: String parameter 'S.s' value 'four of spades' does not match regex '[A-Z][a-z][a-z][a-z ]*'.
ip_regex = '^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$'
email_regex = '^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
class I(param.Parameterized):
ip_address = param.String('192.1.0.1', regex=ip_regex)
email = param.String('example@me.com', regex=email_regex)
i = I()
i.ip_address
'192.1.0.1'
i.ip_address="10.0.0.2"
i.email = "user@gmail.com"
with param.exceptions_summarized():
i.ip_address='192.x.1.x'
ValueError: String parameter 'I.ip_address' value '192.x.1.x' does not match regex '^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$'.
Colors#
param.Color
: Named color or hex RGB string (with or without a # prefix)
A Color parameter specifies one of the standard web color names or an arbitrary hex RGB string. To support only hex RGB strings, specify allow_named=False
.
lemonchiffon
class C(param.Parameterized):
c = param.Color('#EEFF00')
c = C()
c.c
'#EEFF00'
c.c = 'lemonchiffon'
c.c
'lemonchiffon'
with param.exceptions_summarized():
c.c = 'puce'
ValueError: Color parameter 'C.c' only takes RGB hex codes or named colors, received 'puce'.
with param.exceptions_summarized():
c.c = '#abcdefg'
ValueError: Color parameter 'C.c' only takes RGB hex codes or named colors, received '#abcdefg'.
Booleans#
param.Boolean
: A True or False value (or None, if allow_None is true)
A Boolean may be True or False. Like all other Parameters, it can optionally also allow_None
, which will be true by default if the default value is None.
class B(param.Parameterized):
b = param.Boolean(True)
n = param.Boolean(None)
b = B()
b.b
True
with param.exceptions_summarized():
b.b=1
ValueError: Boolean parameter 'B.b' must be True or False, not 1.
with param.exceptions_summarized():
b.b=None
ValueError: Boolean parameter 'B.b' must be True or False, not None.
b.n = True
b.n = None
Numbers#
param.Number
: Python floats, int, and Numpy values.param.Integer
: Python and Numpy integer values.param.Magnitude
: Same asparam.Number(..., bounds=(0.0,1.0))
.param.Date
: Date or datetime value of typedatetime.datetime
,datetime.date
, ornumpy.datetime64
.param.CalendarDate
: Date value of typedatetime.date
.
A Number is the most common type of Parameter. All Numbers in param are of class Dynamic, which allows them to be set not just to a single value but to a value that can repeatedly be drawn from a distribution or a sequence. (See Dynamic Parameters for more information about using these dynamic features, which will not be further discussed here.) Any Number has a default value (potentially None if allowed) and optional bounds.
There are two types of bounds: bounds
and softbounds
. bounds
are hard bounds: the parameter must have a value within the specified range. The default bounds are (None,None), meaning there are actually no hard bounds. One or both bounds can be set by specifying a value (e.g. bounds=(None,10)
means there is no lower bound, and an upper bound of 10). Bounds are inclusive by default, but exclusivity can be specified for each bound by setting inclusive_bounds (e.g. inclusive_bounds=(True,False)
specifies an exclusive upper bound).
When not being dynamically generated, bounds
are checked whenever a Number is created or set. Using a default value outside the hard bounds, or one that is not numeric, results in an exception. When being dynamically generated, bounds are checked when the value of a Number is requested (since it has no specific numeric value when first set). A generated value that is not numeric, or is outside the hard bounds, results in an exception.
A separate set of softbounds
is present to indicate the typical range of the parameter, but these bounds are not enforced by Param. Setting the soft bounds allows a user to know what ranges of values are likely to be useful and allows a GUI to know what values to display on sliders for the Number; softbounds
are thus suggestions or hints rather than enforced limits.
Similarly, an optional step
value can be provided to indicate the granularity of this parameter. As for softbounds
, Param does not force values to conform to the provided step value, but (if provided) the step can be queried by user code and used for parameter sweeps (starting at the softbounds
low and incrementing in value by step
until the softbounds
high), or by GUI code to determine steps on a settings dial.
Several convenience methods for working with bounds are provided:
get_soft_bounds()
: return the soft bounds (or hard bounds, if no soft bounds), for code that needs to know the typical range for this Parameter.crop_to_bounds(val)
: crop the provided value to fit into the hard bounds.set_in_bounds(obj,val)
: silently crop the given value into the legal range and set to the result, for building an API or user interface that accepts free-form input.
Using Number parameters:
import param
class N(param.Parameterized):
n = param.Number(5.6, bounds=(0,None), softbounds=(None,50))
i = param.Integer(5, bounds=(0,50))
a = N()
a.n=2
a.n
2
N.param.n.set_in_bounds(a,-10)
a.n
0
a.param.n.set_in_bounds(a,-5)
a.n
0
a.param.n.set_in_bounds(a,75)
a.n
75
a.param.n.get_soft_bounds()
(0, 50)
with param.exceptions_summarized():
a.n = -5
ValueError: Number parameter 'N.n' must be at least 0, not -5.
a.n = 500
a.n
500
with param.exceptions_summarized():
a.i=5.7
ValueError: Integer parameter 'N.i' must be an integer, not <class 'float'>.
import datetime
class D(param.Parameterized):
d = param.CalendarDate(datetime.date(1900, 1, 1))
t = param.Date(datetime.datetime.fromisoformat('2002-12-25T00:00'))
d = D()
d.d = datetime.date.fromisoformat('2000-01-01')
d.d
datetime.date(2000, 1, 1)
with param.exceptions_summarized():
d.d = 2022
ValueError: CalendarDate parameter 'D.d' only takes date types.
d.t = datetime.date(1900, 1, 1)
d.t
datetime.date(1900, 1, 1)
with param.exceptions_summarized():
d.d = datetime.datetime.fromisoformat('2002-12-25T00:00')
ValueError: CalendarDate parameter 'D.d' only takes date types.
Tuples#
param.Tuple
: Python tuple of a fixed length.param.NumericTuple
: Python tuple of a fixed length, with numeric values.param.XYCoordinates
: Python pair (2-tuple) of numeric values. Same asparam.NumericTuple(..., length=2)
, but semantically representing a 2D coordinate in a plane (e.g. for drawing programs or GUIs)param.Range
:NumericTuple
representing a numeric range with optional bounds and softbounds.param.DateRange
:Range
where the numeric type is a date or datetime (using same date types asparam.Date
).param.CalendarDateRange
:Range
where the numeric type is adatetime.date
.
A tuple Parameter accepts a Python tuple for the value. Tuple parameters have a fixed length, typically set by the default value of the parameter but settable as the length
if the default value is None. Only a tuple of the specified length will be accepted when a value is set.
There are many tuple types as listed above, accepting either any type, numeric types, datetimes, dates, etc. Range
types support bounds
, softbounds
, inclusive_bounds
, and step
on the numeric values in the tuple, similar to Number types.
class T(param.Parameterized):
t = param.Range((-10,10), bounds=(-100,None), softbounds=(None,100))
b = T()
b.t
(-10, 10)
b.t = (50.2,50.3)
b.t
(50.2, 50.3)
with param.exceptions_summarized():
b.t = 5
ValueError: Range parameter 'T.t' only takes a tuple value, not <class 'int'>.
with param.exceptions_summarized():
b.t = (5,5,5)
ValueError: Attribute 'length' of Range parameter 'T.t' is not of the correct length (3 instead of 2).
with param.exceptions_summarized():
b.t = (5,"5")
ValueError: Range parameter 'T.t' only takes numeric values, not <class 'str'>.
with param.exceptions_summarized():
b.t = (-500,500)
ValueError: Range parameter 'T.t' lower bound must be in range [-100, None], not -500.
import datetime
class D(param.Parameterized):
d = param.CalendarDateRange((datetime.date.fromisoformat('1900-01-01'),
datetime.date.fromisoformat('1910-12-31')))
c = D()
c.d
(datetime.date(1900, 1, 1), datetime.date(1910, 12, 31))
with param.exceptions_summarized():
c.d=(1905, 1907)
ValueError: CalendarDateRange parameter 'D.d' only takes date types, not (1905, 1907).
Lists#
param.List
: A Python list of objects, usually of a specified type.param.HookList
: A list of callable objects, for executing user-defined code at some processing stage
List Parameters accept a Python list of objects. Typically the item_type
will be specified for those objects, so that the rest of the code does not have to further check types when it refers to those values. Where appropriate, the bounds
of the list can be set as (min_length, max_length), defaulting to (0,None)
. Because List parameters already have an empty value ([]), they do not support allow_None
.
A param.HookList
is a list whose elements are callable objects (typically either functions or objects with a __call__
method). A HookList
is intended for providing user configurability at various stages of some processing algorithm or pipeline. At present, there is no validation that the provided callable takes any particular number or type of arguments.
import param
class L(param.Parameterized):
ls = param.List(["red","green","blue"], item_type=str, bounds=(0,10))
e = L()
e.ls
['red', 'green', 'blue']
with param.exceptions_summarized():
e.ls = [1,2]
TypeError: List parameter 'L.ls' items must be instances of <class 'str'>, not <class 'int'>.
with param.exceptions_summarized():
e.ls = [str(i) for i in range(20)]
ValueError: List parameter 'L.ls' length must be between 0 and 10 (inclusive), not 20.
class multi_stage_example(param.Parameterized):
before = param.HookList()
during = param.HookList()
after = param.HookList()
values = param.List([1.5,-8.1,6.9,100.0], item_type=float)
def __call__(self):
for h in self.before: h(self)
s = 0
for v in self.values:
v_ = v
for h in self.during: v_ = h(v_)
s += v_
for h in self.after: h()
return s
ex = multi_stage_example()
ex()
100.3
def validate(obj):
for i in obj.values:
if i<0:
print("Negative value found in argument")
m = multi_stage_example(before=[validate])
m()
Negative value found in argument
100.3
from math import fabs
ex.during=[abs]
ex()
116.5
Paths#
param.Path
: A POSIX-style string specifying the location of a local file or folderparam.Filename
: A POSIX-style string specifying the location of a local fileparam.Foldername
: A POSIX-style string specifying the location of a local folder
A Path can be set to a string specifying the path of a file or folder. In code, the string should be specified in POSIX (UNIX) style, using forward slashes / and starting from / if absolute or some other character if relative. When retrieved, the string will be in the format of the user’s operating system.
Relative paths are converted to absolute paths by searching for a matching filename on the filesystem in the current working directory (obtained with os.getcwd()
). If search_paths
is provided and not empty, the folders in that list are searched for the given filename, in order, returning the absolute path for the first match found by appending the provided path to the search path. An IOError is raised if the file or folder is not found. If search_paths
is empty (the default), the file or folder is expected to be in the current working directory.
When check_exists
is set to False
(default is True
) the provided path can optionally exist. This is for instance useful to declare an output file path that is meant to be created at a later stage in a process. In the default case the path must exist, on Parameter instantiation and setting.
Either a file or a folder name is accepted by param.Path
, while param.Filename
accepts only file names and param.Foldername
accepts only folder names.
class P(param.Parameterized):
p = param.Path('Parameter_Types.ipynb')
f = param.Filename('Parameter_Types.ipynb')
d = param.Foldername('lib', search_paths=['/','/usr','/share'], check_exists=False)
o = param.Filename('output.txt', check_exists=False)
p = P()
p.p
'/home/runner/work/param/param/doc/user_guide/Parameter_Types.ipynb'
p.p = 'Outputs.ipynb'
p.p
'/home/runner/work/param/param/doc/user_guide/Outputs.ipynb'
p.f
'/home/runner/work/param/param/doc/user_guide/Parameter_Types.ipynb'
with param.exceptions_summarized():
p.f = '/usr/lib'
OSError: File '/usr/lib' not found.
p.d
'/lib'
with param.exceptions_summarized():
p.d = 'Parameter_Types.ipynb'
p.o # the output file doesn't exist yet
'output.txt'
with open(p.o, 'w') as f:
f.write('Param is awesome!')
p.o # it now exists, getting its value resolve the full file path
'/home/runner/work/param/param/doc/user_guide/output.txt'
Selectors#
param.Selector
: One object selected out of a provided ordered list of objectsparam.ListSelector
: Multiple objects selected out of a provided list of objectsparam.FileSelector
: One filename selected out of those matching a provided globparam.MultiFileSelector
: Multiple filenames selected out of those matching a provided glob
The value of a Selector is one or more items from a set of allowed values. All Selector types must implement get_range()
, providing a concrete list of available options for the value.
A param.Selector
accepts a list or dictionary of objects
, and has a single default (current) value that must be one of those objects. If not otherwise specified, the default will be the first item from the list or dictionary.
Providing the objects as a list is appropriate for selecting among a set of strings, or among a set of Parameterized objects that each have a “name” parameter. That way, a UI that lets users select by string will have a suitable string available for each object to let the user make a choice between them.
Otherwise, the objects should be provided as a name:value dictionary, where the string name will be stored for use in such a UI, but is not otherwise accessed by Param. The values from setting and getting the parameter are always the actual underlying object, not the string names.
To make it easier to modify the collection of objects
, they are wrapped in a container that supports both list-style and dictionary-style methods. This approach ensures that there is a consistent API for updating the objects
and that modifying the objects in place still triggers an event.
If the list of available objects is not meant be exhaustive, you can specify check_on_set=False
(which automatically applies if the initial list is empty). Objects will then be added to the objects
list whenever they are set, including as the initial default. check_on_set=False
can be useful when the predefined set of objects is not exhaustive, letting a user select from the existing list for convenience while also being able to supply any other suitable object they can construct. When check_on_set=True
, the initial value (and all subsequent values) must be in the objects
list.
Because Selector
is usually used to allow selection from a list of existing (instantiated) objects, instantiate
is False by default, but you can specify instantiate=True
if you want each copy of this Parameter value to be independent of other instances and superclasses.
In cases where the objects in the list cannot be known when writing the Parameterized class but can be calculated at runtime, you can supply a callable (of no arguments) to compute_default_fn
, and then ensure that at runtime you call compute_default
on that Parameter to initialize the value.
A param.ListSelector
works just the same as a regular Selector, but the value is a list of valid objects from the available objects, rather than just one. Each item in the list is checked against the objects
, and thus the current value is thus a subset of the objects
, rather than just one of the objects.
A param.FileSelector
works like a regular Selector with the value being a filename and the objects
being computed from files on a file system. The files are specified as a path
glob, and all filenames matching the glob are valid objects
for the parameter.
A param.MultiFileSelector
is the analog of ListSelector but for files, i.e., again supporting a path glob but allowing the user to select a list of filenames rather than a single filename. The default value in this case is all of the matched files, not just the first one.
colors = ["red","green","blue"]
class S(param.Parameterized):
o = param.Selector(objects=colors)
ls = param.ListSelector(colors[0:2], objects=colors)
s = S()
s.o
'red'
s.o = "green"
s.o
'green'
with param.exceptions_summarized():
s.o = "yellow"
ValueError: Selector parameter 'S.o' does not accept 'yellow'; valid options include: '[red, green, blue]'
with param.exceptions_summarized():
s.o = 42
ValueError: Selector parameter 'S.o' does not accept 42; valid options include: '[red, green, blue]'
s.ls
['red', 'green']
s.ls=['blue']
s.ls
['blue']
with param.exceptions_summarized():
s.ls=['red','yellow']
s.ls
ValueError: ListSelector parameter 'S.ls' does not accept 'yellow'; valid options include: '[red, green, blue]'
class F(param.Parameterized):
f = param.FileSelector(path='/usr/share/*')
fs = param.MultiFileSelector(path='/usr/share/*')
f = F()
f.f
'/usr/share/GConf'
f.param.f.objects[0:3]
['/usr/share/GConf', '/usr/share/ImageMagick-6', '/usr/share/PackageKit']
f.fs = f.param.fs.objects[0:2]
f.fs
['/usr/share/GConf', '/usr/share/ImageMagick-6']
ClassSelectors#
param.ClassSelector
: An instance or subclass of a class or tuple of classesparam.Dict
: A Python dictionaryparam.Array
: NumPy arrayparam.Series
: A Pandas Seriesparam.DataFrame
: A Pandas DataFrame
A ClassSelector has a value that is either an instance or a subclass of a specified Python class_
. By default, requires an instance of that class, but specifying is_instance=False
means that a subclass must be selected instead.
Like Selector types, all ClassSelector types implement get_range()
, in this case providing an introspected list of all the concrete (not abstract) subclasses available for the given class. If you want a class to be treated as abstract so that it does not show up in such a list, you can have it declare __abstract=True
as a class attribute. In a GUI, the range list allows a user to select a type of object they want to create, and they can then separately edit the new object’s parameters (if any) to configure it appropriately.
class C(param.Parameterized):
e_instance = param.ClassSelector(default=ZeroDivisionError("1/0"), class_=ArithmeticError)
e_class = param.ClassSelector(
default=ZeroDivisionError, class_=(ArithmeticError, LookupError),
is_instance=False
)
c = C(e_class=OverflowError)
c.e_class, c.e_instance
(OverflowError, ZeroDivisionError('1/0'))
c.param.e_instance.get_range()
OrderedDict([('ArithmeticError', ArithmeticError),
('FloatingPointError', FloatingPointError),
('OverflowError', OverflowError),
('ZeroDivisionError', ZeroDivisionError),
('DecimalException', decimal.DecimalException),
('DivisionByZero', decimal.DivisionByZero),
('DivisionUndefined', decimal.DivisionUndefined),
('Clamped', decimal.Clamped),
('Rounded', decimal.Rounded),
('Inexact', decimal.Inexact),
('Subnormal', decimal.Subnormal),
('FloatOperation', decimal.FloatOperation),
('InvalidOperation', decimal.InvalidOperation),
('Underflow', decimal.Underflow),
('Overflow', decimal.Overflow),
('ConversionSyntax', decimal.ConversionSyntax),
('DivisionImpossible', decimal.DivisionImpossible),
('InvalidContext', decimal.InvalidContext)])
c.param.e_class.get_range()
OrderedDict([('ArithmeticError', ArithmeticError),
('FloatingPointError', FloatingPointError),
('OverflowError', OverflowError),
('ZeroDivisionError', ZeroDivisionError),
('DecimalException', decimal.DecimalException),
('DivisionByZero', decimal.DivisionByZero),
('DivisionUndefined', decimal.DivisionUndefined),
('Clamped', decimal.Clamped),
('Rounded', decimal.Rounded),
('Inexact', decimal.Inexact),
('Subnormal', decimal.Subnormal),
('FloatOperation', decimal.FloatOperation),
('InvalidOperation', decimal.InvalidOperation),
('Underflow', decimal.Underflow),
('Overflow', decimal.Overflow),
('ConversionSyntax', decimal.ConversionSyntax),
('DivisionImpossible', decimal.DivisionImpossible),
('InvalidContext', decimal.InvalidContext),
('LookupError', LookupError),
('IndexError', IndexError),
('KeyError', KeyError),
('CodecRegistryError', encodings.CodecRegistryError),
('NoSuchKernel', jupyter_client.kernelspec.NoSuchKernel),
('UnknownBackend',
IPython.terminal.pt_inputhooks.UnknownBackend)])
with param.exceptions_summarized():
c.e_class = Exception
ValueError: ClassSelector parameter 'C.e_class' value must be a subclass of (ArithmeticError, LookupError), not <class 'Exception'>.
with param.exceptions_summarized():
c.e_instance = ArithmeticError
ValueError: ClassSelector parameter 'C.e_instance' value must be an instance of ArithmeticError, not <class 'ArithmeticError'>.
c.e_instance = ArithmeticError()
c.e_instance
ArithmeticError()
Various types of ClassSelector are provided for specific data types:
param.Dict
:class_=dict
, accepting a Python dictionaryparam.Array
:class=numpy.ndarray
, accepting a NumPy arrayparam.Series
:class_=pandas.Series
, a Pandas Series. Accepts constraints on the number ofrows
, either as an integer length (e.g.rows=10
) or a range tuplerows=(2,4)
).param.DataFrame
:class_=pandas.DataFrame
, a Pandas DataFrame. Accepts constraints on the number ofrows
(as forparam.Series
) orcolumns
(with numerical or range values as forrows
or as a list of column names (which must appear in that order) or as a set of column names (which can appear in any order)).
import numpy as np, pandas as pd
class D(param.Parameterized):
d = param.Dict(dict(a=1, b="not set", c=2.0))
a = param.Array(np.array([1,-1]))
s = param.Series(pd.Series([1,-1]))
f = param.DataFrame(pd.DataFrame({'a':[1,2], 'b':[2,3], 'c':[4,5]}), rows=(2,None), columns=set(['a','b']))
d = D()
d.d = {5:np.nan}
d.d
{5: nan}
with param.exceptions_summarized():
d.d=[("a",1)]
ValueError: Dict parameter 'D.d' value must be an instance of dict, not [('a', 1)].
df = pd.DataFrame({'b':[-2,-3], 'a':[-1,-2]})
d.f = df
d.f
b | a | |
---|---|---|
0 | -2 | -1 |
1 | -3 | -2 |
with param.exceptions_summarized():
df = pd.DataFrame({'a':[-2,-3], 'c':[-1,-2]})
d.f = df
ValueError: DataFrame parameter 'D.f': provided columns ['a', 'c'] does not contain required columns ['a', 'b']
with param.exceptions_summarized():
df = pd.DataFrame({'a':[-2], 'b':[-1]})
d.f = df
ValueError: DataFrame parameter 'D.f': row length 1 does not match declared bounds of (2, None)
classlist
and param.descendents
#
If you are building a GUI or some other mechanism allowing the user to choose a class or an instance of a specified class in a ClassSelector, you may want to construct a list of all subclasses or superclasses of the given class. To make it easy to traverse upwards or downwards in the inheritance hierarchy in this way, param provides the classlist
and param.descendents
functions. classlist
provides a list of the superclasses of the provided object, including itself, in order from least to most specific:
from param.parameterized import classlist
classlist(D)
(object, param.parameterized.Parameterized, __main__.D)
As you can see, D
is a type of Parameterized
, and a Parameterized
is a type of Python object. Conversely (and typically more usefully), param.descendents
provides a list of the subclasses of the provided object, including itself:
param.descendents(param.SelectorBase)
[param.parameters.SelectorBase,
param.parameters.Selector,
param.parameters.ClassSelector,
param.parameters.ObjectSelector,
param.parameters.FileSelector,
param.parameters.ListSelector,
param.parameters.Dict,
param.parameters.Array,
param.parameters.DataFrame,
param.parameters.Series,
param.parameters.MultiFileSelector]
As you can see, there are many subtypes of SelectorBase. This list is calculated from whatever subtypes are currently defined in this Python session. If you derive an additional subtype or load code that defines an additional subtype, this list will get longer, so you need to make sure that all such code has been executed before letting the user make a selection of a subtype.
Invocations#
param.Callable
: A callable object, such as a functionparam.Action
: A callable with no arguments, ready to invokeparam.Event
: Empty action, for use in triggering events for watchersparam.Composite
: Wrapper around other parameters, letting them be set as a tuple
Invocation parameters are a loose group of types that either contain an executable (callable) object, are invoked to execute some other code, or are set to change the value of some other parameter(s) or attribute(s).
A Callable may be set to any callable object, typically either a function or else an instance of a class that provides a __call__
method. At present, there is no validation that the provided callable takes any particular number or type of arguments. Lambdas can be provided, but note that the resulting parameter value will no longer be picklable, so if you need to use pickling (setstate
and getstate
), be sure to use a named function instead.
An Action is the same as a Callable, but is expected to have no arguments. In a GUI an Action is typically mapped to a button whose name or label is the name of this parameter.
An Event Parameter has a Boolean value but is primarily intended for triggering events on its watchers. See Dependencies and Watchers for the details.
A Composite Parameter has a value that is looked up from the value of a list of attributes of this class (which may or may not be parameters) and that when set changes the values of those other attributes or parameters. This type of Parameter can be useful for treating a set of related values as a group for setting purposes, but as individual parameters for code that reads from them. As of Param 1.10, Composite parameters have not been tested with watchers and dependencies and may not behave appropriately for such uses.
def identity(x): return x
def print_time_of_day():
print(datetime.date.today())
class A(param.Parameterized):
transformer = param.Callable(identity)
a = param.Action(print_time_of_day)
def __call__(self, x):
return self.transformer(x)
a = A()
a(5)
5
def double(x):
return 2*x
d = A(transformer=double)
d(5)
10
d.a()
2024-12-16
with param.exceptions_summarized():
d.a = 5
ValueError: Action parameter 'A.a' only takes a callable object, not objects of <class 'int'>.