Skip to content
Snippets Groups Projects
Commit e50f280c authored by Tiago de Freitas Pereira's avatar Tiago de Freitas Pereira
Browse files

Merge branch 'delayed-sample-from-sample' into 'master'

Add a DelayedSample.from_sample classmethod

See merge request !74
parents fd9f0abc c42af936
No related branches found
No related tags found
1 merge request!74Add a DelayedSample.from_sample classmethod
Pipeline #53490 passed
......@@ -89,7 +89,7 @@ class Sample(_ReprMixin):
_copy_attributes(self, parent, kwargs)
class DelayedSample(_ReprMixin):
class DelayedSample(Sample):
"""Representation of sample that can be loaded via a callable.
The optional ``**kwargs`` argument allows you to attach more attributes to
......@@ -168,6 +168,26 @@ class DelayedSample(_ReprMixin):
"""Loads the data from the disk file."""
return self._load()
@classmethod
def from_sample(cls, sample: Sample, **kwargs):
"""Creates a DelayedSample from another DelayedSample or a Sample.
If the sample is a DelayedSample, its data will not be loaded.
Parameters
----------
sample : :any:`Sample`
The sample to convert to a DelayedSample
"""
if hasattr(sample, "_load"):
data = sample._load
else:
def data():
return sample.data
return cls(data, parent=sample, **kwargs)
class SampleSet(MutableSequence, _ReprMixin):
"""A set of samples with extra attributes"""
......
......@@ -117,3 +117,29 @@ def test_delayed_samples():
delayed_sample.annot = "changed"
assert delayed_sample.annot == "changed", delayed_sample.annot
# test DelayedSample.from_smaple
# check if a non-delayed sample is correctly converted to a delayed sample
non_delayed_sample = Sample(1)
delayed_sample = DelayedSample.from_sample(non_delayed_sample, annot="test")
assert delayed_sample.data == 1, delayed_sample.data
assert delayed_sample.annot == "test", delayed_sample.annot
# check if converting a delayed sample will not load the data
raise_error = True
def never_load():
if raise_error:
raise ValueError("never_load should not be called")
return 0
delayed_sample = DelayedSample(
never_load, delayed_attributes=dict(annot=never_load)
)
# should not raise an error when creating the delayed sample
child_sample = DelayedSample.from_sample(delayed_sample)
raise_error = False
assert child_sample.data == 0, child_sample.data
assert child_sample.annot == 0, child_sample.annot
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment