How to use the param.Parameterized function in param

To help you get started, we’ve selected a few param examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github holoviz / param / tests / API0 / testparameterizedrepr.py View on Github external
self.A = A

        class B(param.Parameterized):  # Similar to A but no **kwargs
            a = param.Number(4, precedence=-5)
            b = param.String('B', precedence=-4)
            c = param.Number(4, precedence=0)
            d = param.Integer(-22, precedence=1)

            x = param.Number(1, precedence=2)
            def __init__(self, a, b, c=4, d=-22):
                super(B, self).__init__(a=a, b=b, c=c, name='ClassB')

        self.B = B

        class C(param.Parameterized):  # Similar to A but with *varargs
            a = param.Number(4, precedence=-5)
            b = param.String('B', precedence=-4)
            c = param.Number(4, precedence=0)
            d = param.Integer(-22, precedence=1)

            x = param.Number(1, precedence=2)
            y = param.Number(2, precedence=-1)
            z = param.Number(3, precedence=-2)

            def __init__(self, a, b, c=4, d=-22, *varargs, **kwargs):
                super(C, self).__init__(a=a, b=b, c=c, **kwargs)

        self.C = C


        class D(param.Parameterized):  # Similar to A but with missing parameters
github holoviz / param / tests / API1 / testpandas.py View on Github external
def test_series_row_number_invalid(self):
        valid_series = pandas.Series([1,2])
        invalid_series = pandas.Series([1,2,3])
        class Test(param.Parameterized):
            series = param.Series(default=valid_series, rows=2)

        test = Test()
        exception = "Row length 3 does not match declared bounds of 2"
        with self.assertRaisesRegexp(ValueError, exception):
            test.series = invalid_series
github holoviz / param / tests / API1 / testparamunion.py View on Github external
def test_param_union_warnings(self):
        class A(param.Parameterized):
            a = param.Number(1)
        a = A()
        A(**param.param_union(a))
        self.assertFalse(self.handler.records)
        A(**param.param_union())
        self.assertFalse(self.handler.records)
        A(**param.param_union(a, a))
        self.assertTrue(self.handler.records)
        self.handler.records.pop()
        A(**param.param_union(a, a, warn=False))
        self.assertFalse(self.handler.records)
github holoviz / param / tests / API0 / testdaterangeparam.py View on Github external
def test_wrong_type_default(self):
        try:
            class Q(param.Parameterized):
                a = param.DateRange(default=(1.0,2.0))
        except ValueError:
            pass
        else:
            raise AssertionError("Bad date type was accepted.")
github holoviz / param / tests / API1 / testparameterizedobject.py View on Github external
def test_params(self):
        """Basic tests of params() method."""

        # CB: test not so good because it requires changes if params
        # of PO are changed
        assert 'name' in param.Parameterized.param.params()
        assert len(param.Parameterized.param.params()) in [1,2]

        ## check for bug where subclass Parameters were not showing up
        ## if params() already called on a super class.
        assert 'inst' in TestPO.param.params()
        assert 'notinst' in TestPO.param.params()

        ## check caching
        assert param.Parameterized.param.params() is param.Parameterized().param.params(), "Results of params() should be cached." # just for performance reasons
github holoviz / holoviews / holoviews / plotting / widgets / __init__.py View on Github external
def escape_tuple(vals):
    return "(" + ", ".join(vals) + (",)" if len(vals) == 1 else ")")

def escape_list(vals):
    return "[" + ", ".join(vals) + "]"

def escape_dict(vals):
    vals = [': '.join([k, escape_list(v)]) for k, v in
            zip(escape_vals(vals.keys()), vals.values())]
    return "{" + ", ".join(vals) + "}"


subdirs = [p[0] for p in os.walk(os.path.join(os.path.split(__file__)[0], '..'))]

class NdWidget(param.Parameterized):
    """
    NdWidget is an abstract base class implementing a method to find
    the dimensions and keys of any ViewableElement, GridSpace or
    UniformNdMapping type.  In the process it creates a mock_obj to
    hold the dimensions and keys.
    """

    display_options = param.Dict(default={}, doc="""
        The display options used to generate individual frames""")

    embed = param.Boolean(default=True, doc="""
        Whether to embed all plots in the Javascript, generating
        a static widget not dependent on the IPython server.""")

    #######################
    # JSON export options #
github ioam / lancet / lancet / launch.py View on Github external
made.
        """
        launches = []
        for path in os.listdir(self.output_dir):
            full_path = os.path.join(self.output_dir, path)
            if os.path.isdir(full_path):
                launches.append(self._get_launch_info(full_path))
        self.launches = sorted(launches)



#===========#
# Launchers #
#===========#

class Launcher(core.PrettyPrinted, param.Parameterized):
    """
    A Launcher is constructed using a name, an argument specifier and
    a command template. It can then launch the corresponding tasks
    appropriately when invoked.

    This default Launcher uses subprocess to launch tasks. It is
    intended to illustrate the basic design and should be used as a
    base class for more complex Launchers. In particular all Launchers
    should retain the same behaviour of writing stdout/stderr to the
    streams directory, writing a log file and recording launch
    information.
    """

    batch_name = param.String(default=None, allow_None=True, constant=True,
       doc='''A unique identifier for the current batch''')
github pyviz-topics / EarthSim / earthsim / gssha / model.py View on Github external
ID of default grid supported in GSSHApy. """)

    def get_args(self):
        return {
            'roughness': None,
            'land_use_grid': self.land_use_grid,
            'land_use_to_roughness_table': None,
            'land_use_grid_id': self.land_use_grid_id
        }   
    
    
# Hmm, the "required for new model" bit that was in every docstring makes me think there might
# be another option to consider too, but I haven't got that far yet...


class CreateModel(param.Parameterized):
    """Abstract base class for creating models."""
    __abstract = True
    
    project_base_directory = param.Foldername(default=os.getcwd(), doc="""
       Base directory to which name will be appended to write project files to.""", precedence=0)
    
    project_name = param.String(default='vicksburg_south', doc="""
       Name of project. Required for new model.""")    

    def _map_kw(self,p):
        kw = {}
        kw['project_directory'] = os.path.abspath(os.path.join(p.project_base_directory, p.project_name))
        # Currently allows overwriting existing files
        os.makedirs(kw['project_directory'],exist_ok=True)
        kw['project_name'] = p.project_name
        return kw
github ioam / parambokeh / examples / apps / bokeh / simple.py View on Github external
##### existing parameterized class

import param
import datetime as dt

class Example(param.Parameterized):
    """Example Parameterized class"""
    log = []
    x            = param.Number(default=1.0,bounds=(0,100),precedence=0,doc="X position")
    write_to_log = param.Action(lambda obj: obj.log.append((dt.datetime.now(),obj.x)), 
                                doc="""Record value of x and timestamp.""",precedence=1)

##### create a properties frame for Example

import parambokeh
w = parambokeh.Widgets(Example, mode='server')


##### display value of Example.log in bokeh app

from bokeh.io import curdoc
from bokeh.layouts import layout
github holoviz / panel / panel / pipeline.py View on Github external
if method not in results:
                    results[method] = method()
                result = results[method]
                if index is not None:
                    result = result[index]
                kwargs[name] = result
                outputs.append(name)
            if stage_kwargs.get('inherit_params', self.inherit_params):
                ignored = [stage_kwargs.get(p) or getattr(self, p, None)
                           for p in ('ready_parameter', 'next_parameter')]
                params = [k for k, v in state.param.objects('existing').items()
                          if k not in ignored]
                kwargs.update({k: v for k, v in state.param.get_param_values()
                               if k in stage.param and k != 'name' and k in params})

        if isinstance(stage, param.Parameterized):
            stage.param.set_param(**kwargs)
            self._state = stage
        else:
            self._state = stage(**kwargs)

        # Hide widgets for parameters that are supplied by the previous stage
        for output in outputs:
            self._state.param[output].precedence = -1

        ready_param = stage_kwargs.get('ready_parameter', self.ready_parameter)
        if ready_param and ready_param in stage.param:
            self._state.param.watch(self._unblock, ready_param, onlychanged=False)

        next_param = stage_kwargs.get('next_parameter', self.next_parameter)
        if next_param and next_param in stage.param:
            self._state.param.watch(self._select_next, next_param, onlychanged=False)