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

  • 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():). 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' only takes a string value, not value of type <class 'int'>.
s.s = 'Forever after'
with param.exceptions_summarized():
    s.s = 'four of spades'
ValueError: String parameter '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]?)$'

class I(param.Parameterized):
    ip_address = param.String('192.1.0.1', regex=ip_regex)
i = I()
i.ip_address
'192.1.0.1'
with param.exceptions_summarized():
    i.ip_address='192.x.1.x'
ValueError: String parameter '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 'c' only takes RGB hex codes or named colors, received 'puce'.
with param.exceptions_summarized():
    c.c = '#abcdefg'
ValueError: Color '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' must be True or False, not 1.
with param.exceptions_summarized():
    b.b=None
ValueError: Boolean parameter 'b' must be True or False, not None.
b.n = True
b.n = None

Numbers

  • param.Number: Python floats, int, and bignum values.

  • param.Integer: Integer values.

  • param.Magnitude: Same as param.Number(..., bounds=(0.0,1.0)).

  • param.Date: Date or datetime value of type datetime.datetime, datetime.date, or numpy.datetime64.

  • param.CalendarDate: Date value of type datetime.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.

Numbers support a set_hook that can be set to a function like def logging_set_hook(obj,val): log_value(val) return val, which will be called whenever the value is set.

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: Parameter '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 'i' must be an integer, not type <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' only takes datetime 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')

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 as param.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 as param.Date).

  • param.CalendarDateRange: Range where the numeric type is a datetime.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: Tuple parameter 't' only takes a tuple value, not <class 'int'>.
with param.exceptions_summarized():
    b.t = (5,5,5)
ValueError: Tuple parameter 't' is not of the correct length (3 instead of 2).
with param.exceptions_summarized():
    b.t = (5,"5")
ValueError: NumericTuple parameter 't' only takes numeric values, not type <class 'str'>.
with param.exceptions_summarized():
    b.t = (-500,500)
ValueError: Range parameter 't''s lower bound must be in range [-100, None].
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' 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 'ls' items must be instances of type <class 'str'>, not [1, 2].
with param.exceptions_summarized():
    e.ls = [str(i) for i in range(20)]
ValueError: ls: list length must be between 0 and 10 (inclusive)
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 folder

  • param.Filename: A POSIX-style string specifying the location of a local file

  • param.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. 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.

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'])
    
p = P()
p.p
'/home/runner/work/param/param/doc/user_guide/Parameter_Types.ipynb'
p.p='/usr/lib'
p.p
'/usr/lib'
p.f
'/home/runner/work/param/param/doc/user_guide/Parameter_Types.ipynb'
with param.exceptions_summarized():
    p.f='/usr/lib'
WARNING:param.P.f: File '/usr/lib' not found.
p.d
'/lib'
with param.exceptions_summarized():
    p.d='Parameter_Types.ipynb'
WARNING:param.P.d: Folder Parameter_Types.ipynb was not found in the following place(s): ['/Parameter_Types.ipynb', '/usr/Parameter_Types.ipynb', '/share/Parameter_Types.ipynb'].

Selectors

  • param.Selector: One object selected out of a provided ordered list of objects

  • param.ListSelector: Multiple objects selected out of a provided list of objects

  • param.FileSelector: One filename selected out of those matching a provided glob

  • param.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. Because the string name will need to be looked up from the value if this parameter is used in a UI, all objects need to be hashable via the param.hashable() function, which accepts Python literals plus list and dictionary types (treating them like tuples).

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. If provided, this callable will be invoked, with the result used as the initial value for this Parameter.

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(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: yellow not in parameter o's list of possible objects, valid options include [red, green, blue]
with param.exceptions_summarized():
    s.o = 42
ValueError: 42 not in parameter o's list of possible objects, 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: yellow not in parameter ls's list of possible objects, 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
f.param.f.objects[0:3]
['/usr/share/GConf', '/usr/share/ImageMagick-6', '/usr/share/PackageKit']
f.fs[0:3]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/tmp/ipykernel_3090/3510043419.py in <module>
----> 1 f.fs[0:3]

TypeError: 'NoneType' object is not subscriptable

ClassSelectors

  • param.ClassSelector: An instance or class of a specified Python class or superclass

  • param.Dict: A Python dictionary

  • param.Array: NumPy array

  • param.Series: A Pandas Series

  • param.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(class_=ArithmeticError, default=ZeroDivisionError("1/0"))
    e_class    = param.ClassSelector(class_=ArithmeticError, default=ZeroDivisionError, is_instance=False)
    
c = C(e_class=OverflowError)
c.e_class, c.e_instance
c.param.e_instance.get_range()
c.param.e_class.get_range()
with param.exceptions_summarized():
    c.e_class = Exception
with param.exceptions_summarized():
    c.e_instance = ArithmeticError
c.e_instance = ArithmeticError()
c.e_instance

Various types of ClassSelector are provided for specific data types:

  • param.Dict: class_=dict, accepting a Python dictionary

  • param.Array: class=numpy.ndarray, accepting a NumPy array

  • param.Series: class_=pandas.Series, a Pandas Series. Accepts constraints on the number of rows, either as an integer length (e.g. rows=10) or a range tuple rows=(2,4)).

  • param.DataFrame: class_=pandas.DataFrame, a Pandas DataFrame. Accepts constraints on the number of rows (as for param.Series) or columns (with numerical or range values as for rows 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
with param.exceptions_summarized():
    d.d=[("a",1)]
df = pd.DataFrame({'b':[-2,-3], 'a':[-1,-2]})
d.f = df
d.f
with param.exceptions_summarized():
    df = pd.DataFrame({'a':[-2,-3], 'c':[-1,-2]})
    d.f = df
with param.exceptions_summarized():
    df = pd.DataFrame({'a':[-2], 'b':[-1]})
    d.f = df

Invocations

  • param.Callable: A callable object, such as a function

  • param.Action: A callable with no arguments, ready to invoke

  • param.Event: Empty action, for use in triggering events for watchers

  • param.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)
def double(x):
    return 2*x
    
d = A(transformer=double)
d(5)
d.a()
with param.exceptions_summarized():
    d.a = 5