# param.param Package¶

## param Package¶

Parameters are a kind of class attribute allowing special behavior, including dynamically generated parameter values, documentation strings, constant and read-only parameters, and type or range checking at assignment time.

Potentially useful for any large Python program that needs user-modifiable object attributes; see the Parameter and Parameterized classes for more information. If you do not want to add a dependency on external code by importing from a separately installed param package, you can simply save this file as param.py and copy it and parameterized.py directly into your own package.

This file contains subclasses of Parameter, implementing specific parameter types (e.g. Number), and also imports the definition of Parameters and Parameterized classes.

param.__init__.Action[source]

A user-provided function that can be invoked like a class or object method using (). In a GUI, this might be mapped to a button, but it can be invoked directly as well.

param.__init__.Array[source]

Parameter whose value is a numpy array.

param.__init__.Boolean[source]

Binary or tristate Boolean Parameter.

param.__init__.Callable[source]

Parameter holding a value that is a callable object, such as a function.

A keyword argument instantiate=True should be provided when a function object is used that might have state. On the other hand, regular standalone functions cannot be deepcopied as of Python 2.4, so instantiate must be False for those values.

param.__init__.ClassSelector[source]

Parameter whose value is a specified class or an instance of that class. By default, requires an instance, but if is_instance=False, accepts a class instead. Both class and instance values respect the instantiate slot, though it matters only for is_instance=True.

param.__init__.Composite[source]

A Parameter that is a composite of a set of other attributes of the class.

The constructor argument ‘attribs’ takes a list of attribute names, which may or may not be Parameters. Getting the parameter returns a list of the values of the constituents of the composite, in the order specified. Likewise, setting the parameter takes a sequence of values and sets the value of the constituent attributes.

param.__init__.Dict[source]

Parameter whose value is a dictionary.

param.__init__.Dynamic[source]

Parameter whose value can be generated dynamically by a callable object.

If a Parameter is declared as Dynamic, it can be set a callable object (such as a function or callable class), and getting the parameter’s value will call that callable.

Note that at present, the callable object must allow attributes to be set on itself.

[Python 2.4 limitation: the callable object must be an instance of a callable class, rather than a named function or a lambda function, otherwise the object will not be picklable or deepcopyable.]

If set as time_dependent, setting the Dynamic.time_fn allows the production of dynamic values to be controlled: a new value will be produced only if the current value of time_fn is different from what it was the last time the parameter value was requested.

By default, the Dynamic parameters are not time_dependent so that new values are generated on every call regardless of the time. The default time_fn used when time_dependent is a single Time instance that allows general manipulations of time. It may be set to some other callable as required so long as a number is returned on each call.

param.__init__.FileSelector[source]

Given a path glob, allows one file to be selected from those matching.

param.__init__.Filename[source]

Parameter that can be set to a string specifying the path of a file.

The string should be specified in UNIX style, but it will be returned in the format of the user’s operating system.

The specified path can be absolute, or relative to either:

• any of the paths specified in the search_paths attribute (if search_paths is not None);

or

• any of the paths searched by resolve_path() (if search_paths is None).
param.__init__.Foldername[source]

Parameter that can be set to a string specifying the path of a folder.

The string should be specified in UNIX style, but it will be returned in the format of the user’s operating system.

The specified path can be absolute, or relative to either:

• any of the paths specified in the search_paths attribute (if search_paths is not None);

or

• any of the paths searched by resolve_dir_path() (if search_paths is None).
param.__init__.HookList[source]

Parameter whose value is a list of callable objects.

This type of List Parameter is typically used to provide a place for users to register a set of commands to be called at a specified place in some sequence of processing steps.

class param.__init__.Infinity[source]

Bases: object

An instance of this class represents an infinite value. Unlike Python’s float(‘inf’) value, this object can be safely compared with gmpy numeric types across different gmpy versions.

All operators on Infinity() return Infinity(), apart from the comparison and equality operators. Equality works by checking whether the two objects are both instances of this class.

param.__init__.Integer[source]

Numeric Parameter required to be an Integer

param.__init__.List[source]

Parameter whose value is a list of objects, usually of a specified type.

The bounds allow a minimum and/or maximum length of list to be enforced. If the class is non-None, all items in the list are checked to be of that type.

param.__init__.ListSelector[source]

Variant of ObjectSelector where the value can be multiple objects from a list of possible objects.

param.__init__.Magnitude[source]

Numeric Parameter required to be in the range [0.0-1.0].

param.__init__.MultiFileSelector[source]

Given a path glob, allows multiple files to be selected from the list of matches.

param.__init__.Number[source]

A numeric Dynamic Parameter, with a default value 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).

Number is also a type of Dynamic parameter, so its value can be set to a callable to get a dynamically generated number (see Dynamic).

When not being dynamically generated, bounds are checked when 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 a the value of a Number is requested. A generated value that is not numeric, or is outside the hard bounds, results in an exception.

As a special case, if allow_None=True (which is true by default if the parameter has a default of None when declared) then a value of None is also allowed.

A separate function set_in_bounds() is provided that will silently crop the given value into the legal range, for use in, for instance, a GUI.

softbounds are present to indicate the typical range of the parameter, but are not enforced. Setting the soft bounds allows, for instance, a GUI to know what values to display on sliders for the Number.

Example of creating a Number::
AB = Number(default=0.5, bounds=(None,10), softbounds=(0,1), doc=’Distance from A to B.’)
param.__init__.NumericTuple[source]

A numeric tuple Parameter (e.g. (4.5,7.6,3)) with a fixed tuple length.

param.__init__.ObjectSelector[source]

Parameter whose value must be one object from a list of possible objects.

check_on_set restricts the value to be among the current list of objects. By default, if objects are initially supplied, check_on_set is True, whereas if no objects are initially supplied, check_on_set is False. This can be overridden by explicitly specifying check_on_set initially.

If check_on_set is True (either because objects are supplied initially, or because it is explicitly specified), the default (initial) value must be among the list of objects (unless the default value is None).

param.__init__.Path[source]

Parameter that can be set to a string specifying the path of a file or folder.

The string should be specified in UNIX style, but it will be returned in the format of the user’s operating system. Please use the Filename or Foldername classes if you require discrimination between the two possibilities.

The specified path can be absolute, or relative to either:

• any of the paths specified in the search_paths attribute (if search_paths is not None);

or

• any of the paths searched by resolve_path() (if search_paths is None).
param.__init__.Selector[source]

Parameter whose value must be chosen from a list of possibilities.

Subclasses must implement get_range().

class param.__init__.Time(**params)[source]

params(label=String, time_type=Parameter, timestep=Parameter, unit=String, until=Parameter, name=String)

A callable object returning a number for the current time.

Here ‘time’ is an abstract concept that can be interpreted in any useful way. For instance, in a simulation, it would be the current simulation time, while in a turn-taking game it could be the number of moves so far. The key intended usage is to allow independent Parameterized objects with Dynamic parameters to remain consistent with a global reference.

The time datatype (time_type) is configurable, but should typically be an exact numeric type like an integer or a rational, so that small floating-point errors do not accumulate as time is incremented repeatedly.

When used as a context manager using the ‘with’ statement (implemented by the __enter__ and __exit__ special methods), entry into a context pushes the state of the Time object, allowing the effect of changes to the time value to be explored by setting, incrementing or decrementing time as desired. This allows the state of time-dependent objects to be modified temporarily as a function of time, within the context’s block. For instance, you could use the context manager to “see into the future” to collect data over multiple times, without affecting the global time state once exiting the context. Of course, you need to be careful not to do anything while in context that would affect the lasting state of your other objects, if you want things to return to their starting state when exiting the context.

The starting time value of a new Time object is 0, converted to the chosen time type. Here is an illustration of how time can be manipulated using a Time object:

>>> time = Time(until=20, timestep=1)
>>> 'The initial time is %s' % time()
'The initial time is 0'
>>> 'Setting the time to %s' % time(5)
'Setting the time to 5'
>>> time += 5
>>> 'After incrementing by 5, the time is %s' % time()
'After incrementing by 5, the time is 10'
>>> with time as t:  # Entering a context
...     'Time before iteration: %s' % t()
...     'Iteration: %s' % [val for val in t]
...     'Time after iteration: %s' % t()
...     t += 2
...     'The until parameter may be exceeded outside iteration: %s' % t()
'Time before iteration: 10'
'Iteration: [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]'
'Time after iteration: 20'
'The until parameter may be exceeded outside iteration: 22'
>>> 'After exiting the context the time is back to %s' % time()
'After exiting the context the time is back to 10'


[0m [1;31mParameters changed from their default values are marked in red.[0m [1;36mSoft bound values are marked in cyan.[0m C/V= Constant/Variable, RO/RW = ReadOnly/ReadWrite, AN=Allow None

[1;34mName Value Type Mode [0m

label ‘Time’ String V RW time_type <type ‘int’> Parameter C RW timestep 1.0 Parameter V RW unit None String V RW until Infinity() Parameter V RW

[1;32mParameter docstrings: =====================[0m

[1;34mlabel: The label given to the Time object. Can be used to convey[0m [1;34m more specific notions of time as appropriate. For instance,[0m [1;34m the label could be ‘Simulation Time’ or ‘Duration’.[0m [1;31mtime_type: Callable that Time will use to convert user-specified time[0m [1;31m values into the current time; all times will be of the resulting[0m [1;31m numeric type.[0m [1;31m [0m [1;31m By default, time is of integer type, but you can supply any[0m [1;31m arbitrary-precision type like a fixed-point decimal or a[0m [1;31m rational, to allow fractional times. Floating-point times are[0m [1;31m also allowed, but are not recommended because they will suffer[0m [1;31m from accumulated rounding errors. For instance, incrementing[0m [1;31m a floating-point value 0.0 by 0.05, 20 times, will not reach[0m [1;31m 1.0 exactly. Instead, it will be slightly higher than 1.0,[0m [1;31m because 0.05 cannot be represented exactly in a standard[0m [1;31m floating point numeric type. Fixed-point or rational types[0m [1;31m should be able to handle such computations exactly, avoiding[0m [1;31m accumulation issues over long time intervals.[0m [1;31m [0m [1;31m Some potentially useful exact number classes::[0m [1;31m [0m [1;31m - int: Suitable if all times can be expressed as integers.[0m [1;31m [0m [1;31m - Python’s decimal.Decimal and fractions.Fraction classes:[0m [1;31m widely available but slow and also awkward to specify times[0m [1;31m (e.g. cannot simply type 0.05, but have to use a special[0m [1;31m constructor or a string).[0m [1;31m [0m [1;31m - fixedpoint.FixedPoint: Allows a natural representation of[0m [1;31m times in decimal notation, but very slow and needs to be[0m [1;31m installed separately.[0m [1;31m [0m [1;31m - gmpy.mpq: Allows a natural representation of times in[0m [1;31m decimal notation, and very fast because it uses the GNU[0m [1;31m Multi-Precision library, but needs to be installed[0m [1;31m separately and depends on a non-Python library. gmpy.mpq[0m [1;31m is gmpy’s rational type.[0m [1;34mtimestep: Stepsize to be used with the iterator interface.[0m [1;34m Time can be advanced or decremented by any value, not just[0m [1;34m those corresponding to the stepsize, and so this value is only[0m [1;34m a default.[0m [1;31munit: The units of the time dimensions. The default of None is set[0m [1;31m as the global time function may on an arbitrary time base.[0m [1;31m [0m [1;31m Typical values for the parameter are ‘seconds’ (the SI unit[0m [1;31m for time) or subdivisions thereof (e.g. ‘milliseconds’).[0m [1;34muntil: Declaration of an expected end to time values, if any. When[0m [1;34m using the iterator interface, iteration will end before this[0m [1;34m value is exceeded.[0m

debug(msg, *args, **kw)

Print msg merged with args as a debugging statement.

See Python’s logging module for details of message formatting.

defaults()

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>
get_param_values(onlychanged=False)

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>
inspect_value = <functools.partial object>
message(msg, *args, **kw)

Print msg merged with args as a message.

See Python’s logging module for details of message formatting.

params(parameter_name=None)

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

Includes Parameters from this class and its superclasses.

pprint(imports=None, prefix=' ', unknown_value='<?>', qualify=False, separator='')

(Experimental) Pretty printed representation that may be evaluated with eval. See pprint() function for more details.

print_param_defaults()

Print the default values of all cls’s Parameters.

print_param_values()

Print the values of all this object’s Parameters.

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

Variant of __repr__ designed for generating a runnable script.

set_default(param_name, value)

Set the default value of param_name.

Equivalent to setting param_name on the class.

set_dynamic_time_fn = <functools.partial object>
set_param = <functools.partial object>
state_pop()

Restore the most recently saved state.

See state_push() for more details.

state_push()

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.

time_type

alias of int

verbose(msg, *args, **kw)

Print msg merged with args as a verbose message.

See Python’s logging module for details of message formatting.

warning(msg, *args, **kw)

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

See Python’s logging module for details of message formatting.

param.__init__.Tuple[source]

A tuple Parameter (e.g. (‘a’,7.6,[3,5])) with a fixed tuple length.

param.__init__.XYCoordinates[source]

A NumericTuple for an X,Y coordinate.

param.__init__.abbreviate_paths(pathspec, named_paths)[source]

Given a dict of (pathname,path) pairs, removes any prefix shared by all pathnames. Helps keep menu items short yet unambiguous.

param.__init__.concrete_descendents(parentclass)[source]

Return a dictionary containing all subclasses of the specified parentclass, including the parentclass. Only classes that are defined in scripts that have been run or modules that have been imported are included, so the caller will usually first do from package import *.

Only non-abstract classes will be included.

param.__init__.main = Parameterized(name='main')

Top-level object to allow messaging not tied to a particular Parameterized object, as in ‘param.main.warning(“Invalid option”)’.

class param.__init__.normalize_path(**params)[source]

params(prefix=String, name=String)

Convert a UNIX-style path to the current OS’s format, typically for creating a new file or directory.

If the path is not already absolute, it will be made absolute (using the prefix parameter).

Should do the same as Python’s os.path.abspath(), except using prefix rather than os.getcwd).

[0m [1;31mParameters changed from their default values are marked in red.[0m [1;36mSoft bound values are marked in cyan.[0m C/V= Constant/Variable, RO/RW = ReadOnly/ReadWrite, AN=Allow None

[1;34mName Value Type Mode [0m

prefix ‘/private/tmp/param/doc’ String V RW

[1;32mParameter docstrings: =====================[0m

[1;34mprefix: Prepended to the specified path, if that path is not[0m [1;34m absolute.[0m

debug(msg, *args, **kw)

Print msg merged with args as a debugging statement.

See Python’s logging module for details of message formatting.

defaults()

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>
get_param_values(onlychanged=False)

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>
inspect_value = <functools.partial object>
instance = <functools.partial object>
message(msg, *args, **kw)

Print msg merged with args as a message.

See Python’s logging module for details of message formatting.

params(parameter_name=None)

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

Includes Parameters from this class and its superclasses.

pprint(imports=None, prefix='\n ', unknown_value='<?>', qualify=False, separator='')

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

print_param_defaults()

Print the default values of all cls’s Parameters.

print_param_values()

Print the values of all this object’s Parameters.

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

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

set_default(param_name, value)

Set the default value of param_name.

Equivalent to setting param_name on the class.

set_dynamic_time_fn = <functools.partial object>
set_param = <functools.partial object>
state_pop()

Restore the most recently saved state.

See state_push() for more details.

state_push()

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(msg, *args, **kw)

Print msg merged with args as a verbose message.

See Python’s logging module for details of message formatting.

warning(msg, *args, **kw)

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

See Python’s logging module for details of message formatting.

param.__init__.produce_value(value_obj)[source]

A helper function that produces an actual parameter from a stored object: if the object is callable, call it, otherwise return the object.

class param.__init__.resolve_path(**params)[source]

params(path_to_file=Boolean, search_paths=List, name=String)

Find the path to an existing file, searching the paths specified in the search_paths parameter if the filename is not absolute, and converting a UNIX-style path to the current OS’s format if necessary.

To turn a supplied relative path into an absolute one, the path is appended to paths in the search_paths parameter, in order, until the file is found.

Similar to Python’s os.path.abspath(), except more search paths than just os.getcwd() can be used, and the file must exist.

[0m [1;31mParameters changed from their default values are marked in red.[0m [1;36mSoft bound values are marked in cyan.[0m C/V= Constant/Variable, RO/RW = ReadOnly/ReadWrite, AN=Allow None

[1;34mName Value Type Bounds Mode [0m

path_to_file True Boolean (0, 1) V RW search_paths [‘/private/tmp/param/doc’] List (0, None) V RW

[1;32mParameter docstrings: =====================[0m

[1;34mpath_to_file: String specifying whether the path refers to a ‘File’ or a ‘Folder’.[0m [1;31msearch_paths: Prepended to a non-relative path, in order, until a file is[0m [1;31m found.[0m

debug(msg, *args, **kw)

Print msg merged with args as a debugging statement.

See Python’s logging module for details of message formatting.

defaults()

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>
get_param_values(onlychanged=False)

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>
inspect_value = <functools.partial object>
instance = <functools.partial object>
message(msg, *args, **kw)

Print msg merged with args as a message.

See Python’s logging module for details of message formatting.

params(parameter_name=None)

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

Includes Parameters from this class and its superclasses.

pprint(imports=None, prefix='\n ', unknown_value='<?>', qualify=False, separator='')

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

print_param_defaults()

Print the default values of all cls’s Parameters.

print_param_values()

Print the values of all this object’s Parameters.

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

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

set_default(param_name, value)

Set the default value of param_name.

Equivalent to setting param_name on the class.

set_dynamic_time_fn = <functools.partial object>
set_param = <functools.partial object>
state_pop()

Restore the most recently saved state.

See state_push() for more details.

state_push()

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(msg, *args, **kw)

Print msg merged with args as a verbose message.

See Python’s logging module for details of message formatting.

warning(msg, *args, **kw)

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

See Python’s logging module for details of message formatting.

## ipython Module¶

Optional IPython extension for working with Parameters.

This extension offers extended but completely optional functionality for IPython users. From within IPython, it may be loaded using:

This will register the %params line magic to allow easy inspection of all the parameters defined on a parameterized class or object:

%params <parameterized class or object>

All parameters of the class or object will be listed in the IPython pager together with all their corresponding attributes and docstrings. Note that the class or object to be inspected must already exist in the active namespace.

class param.ipython.ParamPager(metaclass=False)[source]

Bases: object

Callable class that displays information about the supplied Parameterized object or class in the IPython pager.

get_param_info(obj, include_super=True)[source]

Get the parameter dictionary, the list of modifed parameters and the dictionary or parameter values. If include_super is True, parameters are also collected from the super classes.

param_docstrings(info, max_col_len=100, only_changed=False)[source]

Build a string to that presents all of the parameter docstrings in a clean format (alternating red and blue for readability).

## 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.

clear() → None. Remove all items from D.
copy() → a shallow copy of D
extra_keywords()[source]

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

fromkeys(S[, v]) → New dict with keys from S and values equal to v.

v defaults to None.

get(k[, d]) → D[k] if k in D, else d. d defaults to None.
has_key(k) → True if D has a key k, else False
items() → list of D's (key, value) pairs, as 2-tuples
iteritems() → an iterator over the (key, value) items of D
iterkeys() → an iterator over the keys of D
itervalues() → an iterator over the values of D
keys() → list of D's keys
param_keywords()[source]

Return a dictionary containing items from the originally supplied dict_ whose names are parameters of the overridden object (i.e. not extra keywords/parameters).

pop(k[, d]) → v, remove specified key and return the corresponding value.

If key is not found, d is returned if given, otherwise KeyError is raised

popitem() → (k, v), remove and return some (key, value) pair as a

2-tuple; but raise KeyError if D is empty.

setdefault(k[, d]) → D.get(k,d), also set D[k]=d if k not in D
update([E, ]**F) → None. Update D from dict/iterable E and F.

If E present and has a .keys() method, does: for k in E: D[k] = E[k] If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]

values() → list of D's values
viewitems() → a set-like object providing a view on D's items
viewkeys() → a set-like object providing a view on D's keys
viewvalues() → an object providing a view on D's values
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.

mro() → list

return a type’s method resolution order

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

Bases: object

params(name=String)

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.

When initializing a Parameterized instance (‘foo’ in the example above), the values of parameters can be supplied as keyword arguments to the constructor (using parametername=parametervalue); these values will override the class default values for this one instance.

If no ‘name’ parameter is supplied, self.name defaults to the object’s class name with a unique number appended to it.

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.

[0m Object has no parameters.

debug(msg, *args, **kw)[source]

Print msg merged with args as a debugging statement.

See Python’s logging module for details of message formatting.

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>[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>[source]
inspect_value = <functools.partial object>[source]
message(msg, *args, **kw)[source]

Print msg merged with args as a message.

See Python’s logging module for details of message formatting.

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.

pprint(imports=None, prefix=' ', unknown_value='<?>', qualify=False, separator='')[source]

(Experimental) Pretty printed representation that may be evaluated with eval. See pprint() function for more details.

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>[source]
set_param = <functools.partial object>[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(msg, *args, **kw)[source]

Print msg merged with args as a verbose message.

See Python’s logging module for details of message formatting.

warning(msg, *args, **kw)[source]

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

See Python’s logging module for details of message formatting.

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

params(name=String)

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().

[0m Object has no parameters.

debug(msg, *args, **kw)

Print msg merged with args as a debugging statement.

See Python’s logging module for details of message formatting.

defaults()

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>
get_param_values(onlychanged=False)

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>
inspect_value = <functools.partial object>
instance = <functools.partial object>[source]
message(msg, *args, **kw)

Print msg merged with args as a message.

See Python’s logging module for details of message formatting.

params(parameter_name=None)

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

Includes Parameters from this class and its superclasses.

pprint(imports=None, prefix='\n ', unknown_value='<?>', qualify=False, separator='')[source]

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

print_param_defaults()

Print the default values of all cls’s Parameters.

print_param_values()

Print the values of all this object’s Parameters.

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

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

set_default(param_name, value)

Set the default value of param_name.

Equivalent to setting param_name on the class.

set_dynamic_time_fn = <functools.partial object>
set_param = <functools.partial object>
state_pop()

Restore the most recently saved state.

See state_push() for more details.

state_push()

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(msg, *args, **kw)

Print msg merged with args as a verbose message.

See Python’s logging module for details of message formatting.

warning(msg, *args, **kw)

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

See Python’s logging module for details of message formatting.

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.

mro() → list

return a type’s method resolution order

param.parameterized.String[source]

A simple String parameter.

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.)

class param.parameterized.bothmethod(func)[source]

Bases: object

‘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.logging_level(*args, **kwds)[source]

Temporarily modify param’s logging level.

class param.parameterized.overridable_property(fget=None, fset=None, fdel=None, doc=None)[source]

Bases: object

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

param.parameterized.pprint(val, imports, prefix='\n ', settings=[], unknown_value='<?>', qualify=False, separator='')[source]

(Experimental) Pretty printed representation of a parameterized object that may be evaluated with eval.

Similar to repr except introspection of the constructor (__init__) ensures a valid and succinct representation is generated.

Only parameters are represented (whether specified as standard, positional, or keyword arguments). Parameters specified as positional arguments are always shown, followed by modified parameters specified as keyword arguments, sorted by precedence.

unknown_value determines what to do where a representation cannot be generated for something required to recreate the object. Such things include non-parameter positional and keyword arguments, and certain values of parameters (e.g. some random state objects).

Supplying an unknown_value of None causes unrepresentable things to be silently ignored. If unknown_value is a string, that string will appear in place of any unrepresentable things. If unknown_value is False, an Exception will be raised if an unrepresentable value is encountered.

If supplied, imports should be a list, and it will be populated with the set of imports required for the object and all of its parameter values.

If qualify is True, the class’s path will be included (e.g. “a.b.C()”), otherwise only the class will appear (“C()”).

Parameters will be separated by a comma only by default, but the separator parameter allows an additional separator to be supplied (e.g. a newline could be supplied to have each Parameter appear on a separate line).

NOTE: pprint will replace script_repr in a future version of param, but is not yet a complete replacement for script_repr.

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.

The repr of a parameter can be suppressed by returning None from the appropriate hook in script_repr_reg.

param.parameterized.script_repr_reg = {<class 'random.Random'>: <function empty_script_repr>, <type 'list'>: <function container_script_repr>, <type 'mtrand.RandomState'>: <function empty_script_repr>, <type 'function'>: <function function_script_repr>, <type 'tuple'>: <function container_script_repr>}

see script_repr()

class param.parameterized.shared_parameters[source]

Bases: object

Context manager to share parameter instances when creating multiple Parameterized objects of the same type. Parameter default values are instantiated once and cached to be reused when another Parameterized object of the same type is instantiated. Can be useful to easily modify large collections of Parameterized objects at once and can provide a significant speedup.

## version Module¶

Provide consistent and up-to-date __version__ strings for Python packages.

It is easy to forget to update __version__ strings when releasing a project, and it is important that the __version__ strings are useful over the course of development even between releases, especially if releases are infrequent.

This file provides a Version class that addresses both problems. Version is meant to be a simple, bare-bones approach that focuses on (a) ensuring that all declared version information matches for a release, and (b) providing fine-grained version information via a version control system (VCS) in between releases. Other approaches like versioneer.py can automate more of the process of making releases, but they require more complex self-modifying code and code generation techniques than the simple Python class declaration used here.

Currently, the only VCS supported is git, but others could be added easily.

To use Version in a project that provides a Python package named package maintained in a git repository named packagegit:

1. Make the Version class available for import from your package, either by adding the PyPI package “param” as a dependency for your package, or by simply copying this file into package/version.py.

2. Assuming that the current version of your package is 1.0.0, add the following lines to your package/__init__.py:

from param import Version
__version__ = Version(release=(1,0,0), fpath=__file__,
commit="$Format:%h$", reponame="packagegit")


(or from .version import Version if you copied the file directly.)

3. Declare the version as a string in your package’s setup.py file, e.g.:

setup_args["version"]="1.0.0"

4. In your package’s setup.py script code for making a release, add a call to the Version.verify method. E.g.:

setup_args = dict(name='package', version="1.0.0", ...)

if __name__=="__main__":
import package
package.__version__.verify(setup_args['version'])
setup(**setup_args)

1. Tag the version of the repository to be released with a string of the form v*.*, i.e. v1.0.0 in this example. E.g. for git:

git tag -a v1.0.0 -m 'Release version 1.0.0' ; git push


Now when you run setup.py to make a release via something like python setup.py register sdist upload, Python will verify that the version last tagged in the VCS is the same as what is declared in the package and also in setup.py, aborting the release until either the tag is corrected or the declared version is made to match the tag. Releases installed without VCS information will then report the declared release version. If VCS information is available and matches the specified repository name, then the version reported from e.g. str(package.__version__) will provide more detailed information about the precise VCS revision changes since the release. See the docstring for the Version class for more detailed information.

This file is in the public domain, provided as-is, with no warranty of any kind expressed or implied. Anyone is free to copy, modify, publish, use, compile, sell, or distribute it under any license, for any purpose, commercial or non-commercial, and by any means. The original file is maintained at: https://github.com/ioam/param/blob/master/param/version.py

class param.version.Version(release=None, fpath=None, commit=None, reponame=None, commit_count=0)[source]

Bases: object

A simple approach to Python package versioning that supports PyPI releases and additional information when working with version control. When obtaining a package from PyPI, the version returned is a string-formatted rendering of the supplied release tuple. For instance, release (1,0) tagged as v1.0 in the version control system will return 1.0 for str(__version__). Any number of items can be supplied in the release tuple, with either two or three numeric versioning levels typical.

During development, a command like git describe will be used to compute the number of commits since the last version tag, the short commit hash, and whether the commit is dirty (has changes not yet committed). Version tags must start with a lowercase ‘v’ and have a period in them, e.g. v2.0, v0.9.8, v0.1a, or v0.2beta. Note that any non-numeric portion of the version (“a”, “beta”, etc.) will currently be discarded for the purposes of numeric comparisons.

Also note that when version control system (VCS) information is used, the comparison operators take into account the number of commits since the last version tag. This approach is often useful in practice to decide which version is newer for a single developer, but will not necessarily be reliable when comparing against a different fork or branch in a distributed VCS.

For git, if you want version control information available even in an exported archive (e.g. a .zip file from GitHub), you can set the following line in the .gitattributes file of your project:

__init__.py export-subst

abbrev(dev_suffix='')[source]

Abbreviated string representation, optionally declaring whether it is a development version.

commit

A specification for this particular VCS version, e.g. a short git SHA

commit_count

Return the number of commits since the last release

dirty

True if there are uncommited changes, False otherwise

fetch()[source]

Returns a tuple of the major version together with the appropriate SHA and dirty bit (for development version only).

release

Return the release tuple

verify(string_version=None)[source]

Check that the version information is consistent with the VCS before doing a release. If supplied with a string version, this is also checked against the current version. Should be called from setup.py with the declared package version before releasing to PyPI.