ioam/param — pull request #45 by bjodah (2013-03-07 11:44:43+00:00)
Title: Adding convenience function 'from_parametrized_class' to ClassSelector

Dear all,

I tried to figure out how to specify a parameter only accepting a "Parameterized" class.
I found ClassSelector to be what I wanted. But as far as I could see I could not automatically generate a ClassSelector matching my "Parameterized" class. Hence I added the classmethod 'from_parametrized_class' to ClassSelector.

My solution was very simple. (See single commit).

Here is a demo on how to use the function:

import param

class IonType(param.Parameterized):
name = param.String(doc='Human readable name of ion')
charge = param.Integer(0, doc='Charge of ion.')
mass = param.Number(doc='Mass in atomic units.')

class Ion(param.Parameterized):
ion_type = param.ClassSelector.from_parametrized_class(IonType)
coord = param.XYCoordinates(doc='Coordinate of ion.')

sod = IonType(name='Sodium', charge=1, mass=22.99)

ion1 = Ion(ion_type=sod, coord=(1.0, 2.0))
ion2 = Ion(ion_type=sod, coord=(2.0, 5.0))

print ion1.coord
print ion1.ion_type.name
print ion2.coord

not_an_ion_type = {'key': 'value'}

ion3 = Ion(ion_type=not_an_ion_type, coord=(2.0, 5.0))

Which generates the expected output:

(1.0, 2.0)
Sodium
(2.0, 5.0)
Traceback (most recent call last):
File "test.py", line 23, in
ion3 = Ion(ion_type=not_an_ion_type, coord=(2.0, 5.0))
File "/home/bjorn/vc/param/param/parameterized.py", line 866, in __init__
self._setup_params(**params)
File "/home/bjorn/vc/param/param/parameterized.py", line 782, in override_initialization
fn(parameterized_instance,*args,**kw)
File "/home/bjorn/vc/param/param/parameterized.py", line 1207, in _setup_params
setattr(self,name,val)
File "/home/bjorn/vc/param/param/__init__.py", line 746, in __set__
self._check_value(val,obj)
File "/home/bjorn/vc/param/param/__init__.py", line 743, in _check_value
(self._attrib_name, self.class_.__name__, val))
ValueError: Parameter 'ion_type' value must be an instance of IonType, not '{'key': 'value'}'