Skip to content

Commit

Permalink
Make property_available_if a read-only property
Browse files Browse the repository at this point in the history
  • Loading branch information
sebp committed Jun 10, 2023
1 parent 4cf0981 commit 309ef8e
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 89 deletions.
4 changes: 2 additions & 2 deletions sksurv/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from sklearn.pipeline import Pipeline, _final_estimator_has
from sklearn.utils.metaestimators import available_if

from .util import conditionalAvailableProperty
from .util import property_available_if


def _get_version(name):
Expand Down Expand Up @@ -127,7 +127,7 @@ def predict_survival_function(self, X, **kwargs):
return self.steps[-1][-1].predict_survival_function(Xt, **kwargs)


@conditionalAvailableProperty(_final_estimator_has('_predict_risk_score'))
@property_available_if(_final_estimator_has("_predict_risk_score"))
def _predict_risk_score(self):
return self.steps[-1][-1]._predict_risk_score

Expand Down
95 changes: 37 additions & 58 deletions sksurv/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -261,82 +261,61 @@ def safe_concat(objs, *args, **kwargs):
return concatenated


class _ConditionalAvailableProperty:
class _PropertyAvailableIfDescriptor:
"""Implements a conditional property using the descriptor protocol based on the property decorator.
The corresponding class in scikit-learn (_AvailableIfDescriptor) only supports callables. This
class adopts the property decorator as presented by the descriptor guide in the offical documentation.
The corresponding class in scikit-learn (`_AvailableIfDescriptor`) only supports callables.
This class adopts the property decorator as described in the descriptor guide in the offical Python documentation.
The check is defined on the getter function. Setter, Deleter also need to be defined on the exposing clas
s
if they are supposed to be available.
See Also
See also
--------
sklearn.utils.available_if._AvailableIfDescriptor:
The original class in scikit-learn.
https://docs.python.org/3/howto/descriptor.html
Descriptor HowTo Guide
:class:`sklearn.utils.available_if._AvailableIfDescriptor`
The original class in scikit-learn.
"""

def __init__(self, check, fget=None, fset=None, fdel=None, doc=None):
self._check = check
def __init__(self, check, fget, doc=None):
self.check = check
self.fget = fget
self.fset = fset
self.fdel = fdel
if doc is None and fget is not None:
doc = fget.__doc__
self.__doc__ = doc
self._name = ''

def _run_check(self, obj):
attr_err = AttributeError(
f"This {repr(obj)} has no attribute {repr(self._name)}"
)
if not self.check(obj):
raise attr_err
self._name = ""

def __set_name__(self, owner, name):
self._name = name

def __get__(self, obj, objtype=None):
if obj is None:
return self
self._run_check(obj)

attr_err = AttributeError(f"This {obj!r} has no attribute {self._name!r}")
if not self.check(obj):
raise attr_err

if self.fget is None:
raise AttributeError(f"property '{self._name}' has no getter")
return self.fget(obj)

def __set__(self, obj, value):
self._run_check(obj)
if self.fset is None:
raise AttributeError(f"property '{self._name}' has no setter")
self.fset(obj, value)

def __delete__(self, obj):
self._run_check(obj)
if self.fdel is None:
raise AttributeError(f"property '{self._name}' has no deleter")
self.fdel(obj)

@property
def check(self):
return self._check

def getter(self, fget):
prop = type(self)(self.check, fget, self.fset, self.fdel, self.__doc__)
prop._name = self._name
return prop

def setter(self, fset):
prop = type(self)(self.check, self.fget, fset, self.fdel, self.__doc__)
prop._name = self._name
return prop

def deleter(self, fdel):
prop = type(self)(self.check, self.fget, self.fset, fdel, self.__doc__)
prop._name = self._name
return prop


def conditionalAvailableProperty(check):
prop = _ConditionalAvailableProperty(check=check)
return prop.getter

def property_available_if(check):
"""A property attribute that is available only if check returns a truthy value.
Only supports getting an attribute value, setting or deleting an attribute value are not supported.
Parameters
----------
check : callable
When passed the object of the decorated method, this should return
`True` if the property attribute is available, and either return `False`
or raise an `AttributeError` if not available.
Returns
-------
callable
Callable makes the decorated property available if `check` returns
`True`, otherwise the decorated property is unavailable.
"""
return lambda fn: _PropertyAvailableIfDescriptor(check=check, fget=fn)
37 changes: 8 additions & 29 deletions tests/test_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import pytest

from sksurv.testing import FixtureParameterFactory
from sksurv.util import Surv, conditionalAvailableProperty, safe_concat
from sksurv.util import Surv, _PropertyAvailableIfDescriptor, property_available_if, safe_concat


class ConcatCasesFactory(FixtureParameterFactory):
Expand Down Expand Up @@ -377,17 +377,11 @@ def __init__(self, val):
self.avail = False
self._prop = val

@conditionalAvailableProperty(lambda self: self.avail)
@property_available_if(lambda self: self.avail)
def prop(self):
return self._prop

@prop.setter
def prop(self, new):
self._prop = new

@prop.deleter
def prop(self):
self.avail = False
no_prop = _PropertyAvailableIfDescriptor(lambda self: self.avail, fget=None)

testval = 43
msg = "has no attribute 'prop'"
Expand All @@ -397,30 +391,15 @@ def prop(self):
test_obj = WithCondProp(testval)
with pytest.raises(AttributeError, match=msg):
_ = test_obj.prop
with pytest.raises(AttributeError, match=msg):
test_obj.prop = testval - 1
with pytest.raises(AttributeError, match=msg):
del test_obj.prop
assert test_obj.avail is False

test_obj.avail = True
assert test_obj.prop == testval
test_obj.prop = testval - 2
assert test_obj.prop == testval - 2
del test_obj.prop
assert test_obj.avail is False

test_obj.avail = False
with pytest.raises(AttributeError, match=msg):
_ = test_obj.prop
with pytest.raises(AttributeError, match=msg):
test_obj.prop = testval - 3
with pytest.raises(AttributeError, match=msg):
del test_obj.prop

test_obj.avail = True
WithCondProp.prop.fget = None
with pytest.raises(AttributeError, match="has no getter"):
_ = test_obj.prop
WithCondProp.prop.fset = None
with pytest.raises(AttributeError, match="has no setter"):
test_obj.prop = testval - 4
WithCondProp.prop.fdel = None
with pytest.raises(AttributeError, match="has no deleter"):
del test_obj.prop
_ = test_obj.no_prop

0 comments on commit 309ef8e

Please sign in to comment.