param.parameterized

Module

Generic support for objects with full-featured Parameters and messaging.

class param.parameterized.ParamOverrides(overridden, dict_, allow_extra_keywords=False)[source]

Bases: dict

A dictionary that returns the attribute of a specified object if that attribute is not present in itself.

Used to override the parameters of an object.

extra_keywords()[source]

Return a dictionary containing items from the originally supplied dict_ whose names are not parameters of the overridden object.

param.parameterized.Parameter[source]

An attribute descriptor for declaring parameters.

Parameters are a special kind of class attribute. Setting a Parameterized class attribute to be a Parameter instance causes that attribute of the class (and the class’s instances) to be treated as a Parameter. This allows special behavior, including dynamically generated parameter values, documentation strings, constant and read-only parameters, and type or range checking at assignment time.

For example, suppose someone wants to define two new kinds of objects Foo and Bar, such that Bar has a parameter delta, Foo is a subclass of Bar, and Foo has parameters alpha, sigma, and gamma (and delta inherited from Bar). She would begin her class definitions with something like this:

class Bar(Parameterized):
delta = Parameter(default=0.6, doc=’The difference between steps.’) ...
class Foo(Bar):

alpha = Parameter(default=0.1, doc=’The starting value.’) sigma = Parameter(default=0.5, doc=’The standard deviation.’,

constant=True)

gamma = Parameter(default=1.0, doc=’The ending value.’) ...

Class Foo would then have four parameters, with delta defaulting to 0.6.

Parameters have several advantages over plain attributes:

  1. Parameters can be set automatically when an instance is constructed: The default constructor for Foo (and Bar) will accept arbitrary keyword arguments, each of which can be used to specify the value of a Parameter of Foo (or any of Foo’s superclasses). E.g., if a script does this:

    myfoo = Foo(alpha=0.5)

    myfoo.alpha will return 0.5, without the Foo constructor needing special code to set alpha.

    If Foo implements its own constructor, keyword arguments will still be accepted if the constructor accepts a dictionary of keyword arguments (as in def __init__(self,**params):), and then each class calls its superclass (as in super(Foo,self).__init__(**params)) so that the Parameterized constructor will process the keywords.

  2. A Parameterized class need specify only the attributes of a Parameter whose values differ from those declared in superclasses; the other values will be inherited. E.g. if Foo declares

    delta = Parameter(default=0.2)

    the default value of 0.2 will override the 0.6 inherited from Bar, but the doc will be inherited from Bar.

  3. The Parameter descriptor class can be subclassed to provide more complex behavior, allowing special types of parameters that, for example, require their values to be numbers in certain ranges, generate their values dynamically from a random distribution, or read their values from a file or other external source.

  4. The attributes associated with Parameters provide enough information for automatically generating property sheets in graphical user interfaces, allowing Parameterized instances to be edited by users.

Note that Parameters can only be used when set as class attributes of Parameterized classes. Parameters used as standalone objects, or as class attributes of non-Parameterized classes, will not have the behavior described here.

class param.parameterized.ParameterMetaclass[source]

Bases: type

Metaclass allowing control over creation of Parameter classes.

class param.parameterized.Parameterized(**params)[source]

Bases: object

Base class for named objects that support Parameters and message formatting.

Automatic object naming: Every Parameterized instance has a name parameter. If the user doesn’t designate a name=<str> argument when constructing the object, the object will be given a name consisting of its class name followed by a unique 5-digit number.

Automatic parameter setting: The Parameterized __init__ method will automatically read the list of keyword parameters. If any keyword matches the name of a Parameter (see Parameter class) defined in the object’s class or any of its superclasses, that parameter in the instance will get the value given as a keyword argument. For example:

class Foo(Parameterized):
xx = Parameter(default=1)

foo = Foo(xx=20)

in this case foo.xx gets the value 20.

Message formatting: Each Parameterized instance has several methods for optionally printing output. This functionality is based on the standard Python ‘logging’ module; using the methods provided here, wraps calls to the ‘logging’ module’s root logger and prepends each message with information about the instance from which the call was made. For more information on how to set the global logging level and change the default message prefix, see documentation for the ‘logging’ module.

debug(*args)[source]

Print the arguments as a debugging statement.

defaults()[source]

Return {parameter_name:parameter.default} for all non-constant Parameters.

Note that a Parameter for which instantiate==True has its default instantiated.

force_new_dynamic_value = <functools.partial object at 0x2b2c216f75d0>[source]
get_param_values(onlychanged=False)[source]

Return a list of name,value pairs for all Parameters of this object.

If onlychanged is True, will only return values that are not equal to the default value.

get_value_generator = <functools.partial object at 0x2b2c216f7628>[source]
inspect_value = <functools.partial object at 0x2b2c216f7680>[source]
message(*args)[source]

Print the arguments as a message.

classmethod params(parameter_name=None)[source]

Return the Parameters of this class as the dictionary {name: parameter_object}

Includes Parameters from this class and its superclasses.

classmethod print_param_defaults()[source]

Print the default values of all cls’s Parameters.

print_param_values()[source]

Print the values of all this object’s Parameters.

script_repr(imports=[], prefix=' ')[source]

Variant of __repr__ designed for generating a runnable script.

classmethod set_default(param_name, value)[source]

Set the default value of param_name.

Equivalent to setting param_name on the class.

set_dynamic_time_fn = <functools.partial object at 0x2b2c216f76d8>[source]
set_param = <functools.partial object at 0x2b2c216f7788>[source]
state_pop()[source]

Restore the most recently saved state.

See state_push() for more details.

state_push()[source]

Save this instance’s state.

For Parameterized instances, this includes the state of dynamically generated values.

Subclasses that maintain short-term state should additionally save and restore that state using state_push() and state_pop().

Generally, this method is used by operations that need to test something without permanently altering the objects’ state.

verbose(*args)[source]

Print the arguments as a verbose message.

warning(*args)[source]

Print the arguments as a warning, unless module variable warnings_as_exceptions is True, then raise an Exception containing the arguments.

class param.parameterized.ParameterizedFunction(**params)[source]

Bases: param.parameterized.Parameterized

Acts like a Python function, but with arguments that are Parameters.

Implemented as a subclass of Parameterized that, when instantiated, automatically invokes __call__ and returns the result, instead of returning an instance of the class.

To obtain an instance of this class, call instance().

instance = <functools.partial object at 0x2b2c216f76d8>[source]
script_repr(imports=[], prefix=' ')[source]

Same as Parameterized.script_repr, except that X.classname(Y is replaced with X.classname.instance(Y

class param.parameterized.ParameterizedMetaclass(mcs, name, bases, dict_)[source]

Bases: type

The metaclass of Parameterized (and all its descendents).

The metaclass overrides type.__setattr__ to allow us to set Parameter values on classes without overwriting the attribute descriptor. That is, for a Parameterized class of type X with a Parameter y, the user can type X.y=3, which sets the default value of Parameter y to be 3, rather than overwriting y with the constant value 3 (and thereby losing all other info about that Parameter, such as the doc string, bounds, etc.).

The __init__ method is used when defining a Parameterized class, usually when the module where that class is located is imported for the first time. That is, the __init__ in this metaclass initializes the class object, while the __init__ method defined in each Parameterized class is called for each new instance of that class.

Additionally, a class can declare itself abstract by having an attribute __abstract set to True. The ‘abstract’ attribute can be used to find out if a class is abstract or not.

abstract

Return True if the class has an attribute __abstract set to True. Subclasses will return False unless they themselves have __abstract set to true. This mechanism allows a class to declare itself to be abstract (e.g. to avoid it being offered as an option in a GUI), without the “abstract” property being inherited by its subclasses (at least one of which is presumably not abstract).

get_param_descriptor(mcs, param_name)[source]

Goes up the class hierarchy (starting from the current class) looking for a Parameter class attribute param_name. As soon as one is found as a class attribute, that Parameter is returned along with the class in which it is declared.

param.parameterized.String[source]

An attribute descriptor for declaring parameters.

Parameters are a special kind of class attribute. Setting a Parameterized class attribute to be a Parameter instance causes that attribute of the class (and the class’s instances) to be treated as a Parameter. This allows special behavior, including dynamically generated parameter values, documentation strings, constant and read-only parameters, and type or range checking at assignment time.

For example, suppose someone wants to define two new kinds of objects Foo and Bar, such that Bar has a parameter delta, Foo is a subclass of Bar, and Foo has parameters alpha, sigma, and gamma (and delta inherited from Bar). She would begin her class definitions with something like this:

class Bar(Parameterized):
delta = Parameter(default=0.6, doc=’The difference between steps.’) ...
class Foo(Bar):

alpha = Parameter(default=0.1, doc=’The starting value.’) sigma = Parameter(default=0.5, doc=’The standard deviation.’,

constant=True)

gamma = Parameter(default=1.0, doc=’The ending value.’) ...

Class Foo would then have four parameters, with delta defaulting to 0.6.

Parameters have several advantages over plain attributes:

  1. Parameters can be set automatically when an instance is constructed: The default constructor for Foo (and Bar) will accept arbitrary keyword arguments, each of which can be used to specify the value of a Parameter of Foo (or any of Foo’s superclasses). E.g., if a script does this:

    myfoo = Foo(alpha=0.5)

    myfoo.alpha will return 0.5, without the Foo constructor needing special code to set alpha.

    If Foo implements its own constructor, keyword arguments will still be accepted if the constructor accepts a dictionary of keyword arguments (as in def __init__(self,**params):), and then each class calls its superclass (as in super(Foo,self).__init__(**params)) so that the Parameterized constructor will process the keywords.

  2. A Parameterized class need specify only the attributes of a Parameter whose values differ from those declared in superclasses; the other values will be inherited. E.g. if Foo declares

    delta = Parameter(default=0.2)

    the default value of 0.2 will override the 0.6 inherited from Bar, but the doc will be inherited from Bar.

  3. The Parameter descriptor class can be subclassed to provide more complex behavior, allowing special types of parameters that, for example, require their values to be numbers in certain ranges, generate their values dynamically from a random distribution, or read their values from a file or other external source.

  4. The attributes associated with Parameters provide enough information for automatically generating property sheets in graphical user interfaces, allowing Parameterized instances to be edited by users.

Note that Parameters can only be used when set as class attributes of Parameterized classes. Parameters used as standalone objects, or as class attributes of non-Parameterized classes, will not have the behavior described here.

param.parameterized.add_metaclass(metaclass)[source]

Class decorator for creating a class with a metaclass.

param.parameterized.all_equal(arg1, arg2)[source]

Return a single boolean for arg1==arg2, even for numpy arrays using element-wise comparison.

Uses all(arg1==arg2) for sequences, and arg1==arg2 otherwise.

If both objects have an ‘_infinitely_iterable’ attribute, they are not be zipped together and are compared directly instead.

param.parameterized.as_uninitialized(fn)[source]

Decorator: call fn with the parameterized_instance’s initialization flag set to False, then revert the flag.

(Used to decorate Parameterized methods that must alter a constant Parameter.)

param.parameterized.bothmethod[source]

‘optional @classmethod’

A decorator that allows a method to receive either the class object (if called on the class) or the instance object (if called on the instance) as its first argument.

Code (but not documentation) copied from: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/523033.

param.parameterized.classlist(class_)[source]

Return a list of the class hierarchy above (and including) the given class.

Same as inspect.getmro(class_)[::-1]

param.parameterized.dbprint_prefix = None

If not None, the value of this Parameter will be called (using ‘()’) before every call to __db_print, and is expected to evaluate to a string that is suitable for prefixing messages and warnings (such as some indicator of the global state).

param.parameterized.descendents(class_)[source]

Return a list of the class hierarchy below (and including) the given class.

The list is ordered from least- to most-specific. Can be useful for printing the contents of an entire class hierarchy.

param.parameterized.get_all_slots(class_)[source]

Return a list of slot names for slots defined in class_ and its superclasses.

param.parameterized.get_occupied_slots(instance)[source]

Return a list of slots for which values have been set.

(While a slot might be defined, if a value for that slot hasn’t been set, then it’s an AttributeError to request the slot’s value.)

param.parameterized.overridable_property[source]

The same as Python’s “property” attribute, but allows the accessor methods to be overridden in subclasses.

param.parameterized.print_all_param_defaults()[source]

Print the default values for all imported Parameters.

param.parameterized.script_repr(val, imports, prefix, settings)[source]

Variant of repr() designed for generating a runnable script.

Instances of types that require special handling can use the script_repr_reg dictionary. Using the type as a key, add a function that returns a suitable representation of instances of that type, and adds the required import statement.

param.parameterized.script_repr_reg = {<type 'tuple'>: <function container_script_repr at 0x2b2c19f86a28>, <type 'function'>: <function function_script_repr at 0x2b2c19f86aa0>, <type 'list'>: <function container_script_repr at 0x2b2c19f86a28>}

see script_repr()