Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Re-validate default when Parameter type changes on subclass #812

Merged
merged 4 commits into from
Aug 2, 2023
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 22 additions & 11 deletions param/parameterized.py
Original file line number Diff line number Diff line change
Expand Up @@ -3153,8 +3153,7 @@ def _initialize_parameter(mcs,param_name,param):
# A Parameter has no way to find out the name a
# Parameterized class has for it
param._set_names(param_name)
mcs.__param_inheritance(param_name,param)

mcs.__param_inheritance(param_name, param)

# Should use the official Python 2.6+ abstract base classes; see
# https://github.com/holoviz/param/issues/84
Expand Down Expand Up @@ -3249,7 +3248,7 @@ def __setattr__(mcs, attribute_name, value):
if isinstance(value,Parameter):
mcs.__param_inheritance(attribute_name,value)

def __param_inheritance(mcs,param_name,param):
def __param_inheritance(mcs, param_name, param):
"""
Look for Parameter values in superclasses of this
Parameterized class.
Expand Down Expand Up @@ -3281,27 +3280,35 @@ def __param_inheritance(mcs,param_name,param):
# get all relevant slots (i.e. slots defined in all
# superclasses of this parameter)
slots = {}
for p_class in classlist(type(param))[1::]:
p_type = type(param)
for i, p_class in enumerate(classlist(p_type)[1::]):
slots.update(dict.fromkeys(p_class.__slots__))
philippjfr marked this conversation as resolved.
Show resolved Hide resolved


# note for some eventual future: python 3.6+ descriptors grew
# __set_name__, which could replace this and _set_names
setattr(param,'owner',mcs)
setattr(param, 'owner', mcs)
del slots['owner']

# backwards compatibility (see Composite parameter)
if 'objtype' in slots:
setattr(param,'objtype',mcs)
setattr(param, 'objtype', mcs)
del slots['objtype']

supers = classlist(mcs)[::-1]

# instantiate is handled specially
# Explicitly inherit instantiate from super class and
# check if type has changed to a more specific or different
# Parameter type, requiring extra validation
type_change = False
for superclass in supers:
super_param = superclass.__dict__.get(param_name)
if isinstance(super_param, Parameter) and super_param.instantiate is True:
param.instantiate=True
if not isinstance(super_param, Parameter):
continue
if super_param.instantiate is True:
param.instantiate = True
super_type = type(super_param)
if not issubclass(super_type, p_type):
type_change = True
del slots['instantiate']

callables = {}
Expand Down Expand Up @@ -3346,6 +3353,11 @@ def __param_inheritance(mcs,param_name,param):
# that need updates to make sure they're set up correctly after inheritance.
param._update_state()

# If the type has changed to a more specific or different type
# validate the default again.
if type_change:
param._validate(param.default)

def get_param_descriptor(mcs,param_name):
"""
Goes up the class hierarchy (starting from the current class)
Expand All @@ -3362,7 +3374,6 @@ def get_param_descriptor(mcs,param_name):




# Whether script_repr should avoid reporting the values of parameters
# that are just inheriting their values from the class defaults.
# Because deepcopying creates a new object, cannot detect such
Expand Down
53 changes: 36 additions & 17 deletions tests/testparameterizedobject.py
Original file line number Diff line number Diff line change
Expand Up @@ -1051,7 +1051,7 @@ class A(param.Parameterized):
p = param.String(doc='1')

class B(A):
p = param.Number()
p = param.Number(default=0.1)

b = B()

Expand All @@ -1075,24 +1075,23 @@ class A(param.Parameterized):
p = param.String(default='1')

class B(A):
p = param.Number()
p = param.Number(default=0.1)

b = B()

# Could argue this should not be allowed.
assert b.p == '1'
assert b.p == 0.1


def test_inheritance_default_is_None_in_sub():
class A(param.Parameterized):
p = param.String(default='1')
p = param.Tuple(default=(0, 1))

class B(A):
p = param.Action()
p = param.NumericTuple()

b = B()

assert b.p == '1'
assert b.p == (0, 1)


def test_inheritance_diamond_not_supported():
Expand Down Expand Up @@ -1142,6 +1141,26 @@ class D(B, C):
assert d.param.p.doc == '11'


def test_inheritance_with_incompatible_defaults():
class A(param.Parameterized):
p = param.String()

with pytest.raises(ValueError) as excinfo:
class B(A):
p = param.Number()
assert "Parameter 'p' only takes numeric values, not type <class 'str'>" in str(excinfo.value)


def test_inheritance_default_validation_with_more_specific_type():
class A(param.Parameterized):
p = param.Tuple(default=('a', 'b'))

with pytest.raises(ValueError) as excinfo:
class B(A):
p = param.NumericTuple()
assert "NumericTuple parameter 'p' only takes numeric values, not type <class 'str'>" in str(excinfo.value)


def test_inheritance_from_multiple_params_class():
class A(param.Parameterized):
p = param.Parameter(doc='foo')
Expand Down Expand Up @@ -1171,25 +1190,25 @@ class A(param.Parameterized):
p = param.Parameter(doc='foo')

class B(A):
p = param.Action(default=2)
p = param.Dict(default={'foo': 'bar'})

class C(B):
p = param.Date(instantiate=True)
p = param.ClassSelector(class_=object, allow_None=True)

a = A()
b = B()
c = C()

assert a.param.p.instantiate is False
assert a.param.p.allow_None is True
assert a.param.p.default is None
assert a.param.p.doc == 'foo'

assert b.param.p.instantiate is False
assert b.param.p.default == 2
assert b.param.p.allow_None is False
assert b.param.p.default == {'foo': 'bar'}
assert b.param.p.doc == 'foo'

assert c.param.p.instantiate is True
assert c.param.p.default == 2
assert c.param.p.allow_None is True
assert c.param.p.default == {'foo': 'bar'}
assert c.param.p.doc == 'foo'


Expand All @@ -1201,12 +1220,12 @@ class A(param.Parameterized):
A.param.p.doc = 'bar'

class B(A):
p = param.Action(default=2)
p = param.Dict(default={'foo': 'bar'})

assert A.param.p.default == 1
assert A.param.p.doc == 'bar'

assert B.param.p.default == 2
assert B.param.p.default == {'foo': 'bar'}
assert B.param.p.doc == 'bar'

a = A()
Expand All @@ -1215,7 +1234,7 @@ class B(A):
assert a.param.p.default == 1
assert a.param.p.doc == 'bar'

assert b.param.p.default == 2
assert b.param.p.default == {'foo': 'bar'}
assert b.param.p.doc == 'bar'


Expand Down