Skip to content

Commit 536505d

Browse files
authored
Merge pull request #1452 from zm711/assert-errors
Convert Asserts to Errors
2 parents 84b672c + 8501846 commit 536505d

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

49 files changed

+516
-267
lines changed

neo/core/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,8 @@
5151
from neo.core.view import ChannelView
5252
from neo.core.group import Group
5353

54+
from neo.core.baseneo import NeoReadWriteError
55+
5456
# Block should always be first in this list
5557
objectlist = [
5658
Block,

neo/core/baseneo.py

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,27 @@
3434
class MergeError(Exception):
3535
pass
3636

37+
class NeoReadWriteError(IOError):
38+
"""
39+
This is the main neo-specific error that has to deal with
40+
ephys data that does not follow the requirements for the Neo
41+
object hierarchy.
42+
43+
It should be used for:
44+
1) When an IO does not support a specific read/write functionality
45+
2) A file format does not support the structural requirements
46+
* Different sampling rates among streams
47+
* Different expectations for a file format (could also be
48+
a NotImplementedError depending on circumstances)
49+
50+
It should NOT be used when other errors more accurately describe
51+
the problem:
52+
1) ValueError: for incorrect values (like t_start, t_stop)
53+
2) TypeError: use of an inappropriate type for an argument
54+
3) FileNotFoundError: for use when a file is not found
55+
"""
56+
pass
57+
3758

3859
def _check_annotations(value):
3960
"""
@@ -68,7 +89,8 @@ def merge_annotation(a, b):
6889
For strings: concatenate with ';'
6990
Otherwise: fail if the annotations are not equal
7091
"""
71-
assert type(a) == type(b), f"type({a})) {type(a)} != type({b}) {type(b)}"
92+
if type(a) != type(b):
93+
raise TypeError(f"type({a}) {type(a)} != type({b}) {type(b)}")
7294
if isinstance(a, dict):
7395
return merge_annotations(a, b)
7496
elif isinstance(a, np.ndarray): # concatenate b to a
@@ -81,7 +103,8 @@ def merge_annotation(a, b):
81103
else:
82104
return a + ";" + b
83105
else:
84-
assert a == b, f"{a} != {b}"
106+
if a != b:
107+
raise ValueError(f"{a} != {b}")
85108
return a
86109

87110

@@ -131,7 +154,8 @@ def intersect_annotations(A, B):
131154

132155
for key in set(A.keys()) & set(B.keys()):
133156
v1, v2 = A[key], B[key]
134-
assert type(v1) == type(v2), f"type({v1}) {type(v1)} != type({v2}) {type(v2)}"
157+
if type(v1) != type(v2):
158+
raise TypeError(f"type({v1}) {type(v1)} != type({v2}) {type(v2)}")
135159
if isinstance(v1, dict) and v1 == v2:
136160
result[key] = deepcopy(v1)
137161
elif isinstance(v1, str) and v1 == v2:

neo/core/container.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -450,7 +450,8 @@ def check_relationships(self, recursive=True):
450450
else:
451451
container = getattr(self, _container_name(child.__class__.__name__))
452452
if container.parent is not None:
453-
assert getattr(child, parent_name, None) is self
453+
if getattr(child, parent_name, None) is not self:
454+
raise AttributeError("Child should have its parent as an attribute")
454455
if recursive:
455456
for child in self.container_children:
456457
child.check_relationships(recursive=True)

neo/core/objectlist.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,8 @@ def __init__(self, allowed_contents, parent=None):
1919
self.allowed_contents = (allowed_contents,)
2020
else:
2121
for item in allowed_contents:
22-
assert issubclass(item, BaseNeo)
22+
if not issubclass(item, BaseNeo):
23+
raise TypeError("Each item in allowed_contents must be a subclass of BaseNeo")
2324
self.allowed_contents = tuple(allowed_contents)
2425
self._items = []
2526
self.parent = parent

neo/core/spiketrain.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -891,8 +891,8 @@ def _merge_array_annotations(self, others, sorting=None):
891891
the spikes.
892892
:return Merged array_annotations
893893
"""
894-
895-
assert sorting is not None, "The order of the merged spikes must be known"
894+
if sorting is None:
895+
raise ValueError("The order of the merged spikes must be known")
896896

897897
merged_array_annotations = {}
898898

neo/core/spiketrainlist.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -87,8 +87,8 @@ def __init__(self, items=None, parent=None):
8787
self._channel_id_array = None
8888
self._all_channel_ids = None
8989
self._spiketrain_metadata = {}
90-
if parent is not None:
91-
assert parent.__class__.__name__ == "Segment"
90+
if parent is not None and parent.__class__.__name__ != "Segment":
91+
raise AttributeError("The parent class must be a Segment")
9292
self.segment = parent
9393

9494
@property

neo/io/asciispiketrainio.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
import quantities as pq
1515

1616
from neo.io.baseio import BaseIO
17-
from neo.core import Segment, SpikeTrain
17+
from neo.core import Segment, SpikeTrain, NeoReadWriteError
1818

1919

2020
class AsciiSpikeTrainIO(BaseIO):
@@ -91,7 +91,8 @@ def read_segment(
9191
t_start : time start of all spiketrain 0 by default
9292
unit : unit of spike times, can be a str or directly a Quantities
9393
"""
94-
assert not lazy, "Do not support lazy"
94+
if lazy:
95+
raise NeoReadWriteError("This IO does not support lazy reading")
9596

9697
unit = pq.Quantity(1, unit)
9798

neo/io/basefromrawio.py

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -241,13 +241,10 @@ def read_segment(
241241
"""
242242

243243
if lazy:
244-
assert (
245-
time_slice is None
246-
), "For lazy=True you must specify a time_slice when LazyObject.load(time_slice=...)"
247-
248-
assert (
249-
not load_waveforms
250-
), "For lazy=True you must specify load_waveforms when SpikeTrain.load(load_waveforms=...)"
244+
if time_slice is not None:
245+
raise ValueError("For lazy=True you must specify a time_slice when LazyObject.load(time_slice=...)")
246+
if load_waveforms:
247+
raise ValueError("For lazy=True you must specify load_waveforms when SpikeTrain.load(load_waveforms=...)")
251248

252249
if signal_group_mode is None:
253250
signal_group_mode = self._prefered_signal_group_mode

neo/io/baseio.py

Lines changed: 59 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535
RectangularRegionOfInterest,
3636
CircularRegionOfInterest,
3737
PolygonRegionOfInterest,
38+
NeoReadWriteError
3839
)
3940

4041
read_error = "This type is not supported by this file format for reading"
@@ -139,7 +140,7 @@ def read(self, lazy: bool = False, **kargs):
139140
Returns all the data from the file as Blocks
140141
"""
141142
if lazy and not self.support_lazy:
142-
raise ValueError("This IO module does not support lazy loading")
143+
raise NeoReadWriteError("This IO module does not support lazy loading")
143144
if Block in self.readable_objects:
144145
if hasattr(self, "read_all_blocks") and callable(getattr(self, "read_all_blocks")):
145146
return self.read_all_blocks(lazy=lazy, **kargs)
@@ -167,97 +168,121 @@ def write(self, bl, **kargs):
167168
"""
168169
if Block in self.writeable_objects:
169170
if isinstance(bl, Sequence):
170-
assert hasattr(
171-
self, "write_all_blocks"
172-
), f"{self.__class__.__name__} does not offer to store a sequence of blocks"
171+
if not hasattr(self, "write_all_blocks"):
172+
raise NeoReadWriteError(f"{self.__class__.__name__} does not offer to store a sequence of blocks")
173173
self.write_all_blocks(bl, **kargs)
174174
else:
175175
self.write_block(bl, **kargs)
176176
elif Segment in self.writeable_objects:
177-
assert len(bl.segments) == 1, (
178-
f"{self.__class__.__name__} is based on segment so if you try to write a block it "
179-
+ "must contain only one Segment"
180-
)
177+
if len(bl.segments) != 1:
178+
raise NeoReadWriteError(f"{self.__class__.__name__} is based on segment so if you try to write a block it "
179+
+ "must contain only one Segment")
181180
self.write_segment(bl.segments[0], **kargs)
182181
else:
183182
raise NotImplementedError
184183

185184
######## All individual read methods #######################
186185
def read_block(self, **kargs):
187-
assert Block in self.readable_objects, read_error
186+
if Block not in self.readable_objects:
187+
raise NeoReadWriteError(read_error)
188188

189189
def read_segment(self, **kargs):
190-
assert Segment in self.readable_objects, read_error
190+
if Segment not in self.readable_objects:
191+
raise NeoReadWriteError(read_error)
191192

192193
def read_spiketrain(self, **kargs):
193-
assert SpikeTrain in self.readable_objects, read_error
194+
if SpikeTrain not in self.readable_objects:
195+
raise NeoReadWriteError(read_error)
194196

195197
def read_analogsignal(self, **kargs):
196-
assert AnalogSignal in self.readable_objects, read_error
198+
if AnalogSignal not in self.readable_objects:
199+
raise NeoReadWriteError(read_error)
197200

198201
def read_imagesequence(self, **kargs):
199-
assert ImageSequence in self.readable_objects, read_error
202+
if ImageSequence not in self.readable_objects:
203+
raise NeoReadWriteError(read_error)
200204

201205
def read_rectangularregionofinterest(self, **kargs):
202-
assert RectangularRegionOfInterest in self.readable_objects, read_error
206+
if RectangularRegionOfInterest not in self.readable_objects:
207+
raise NeoReadWriteError(read_error)
203208

204209
def read_circularregionofinterest(self, **kargs):
205-
assert CircularRegionOfInterest in self.readable_objects, read_error
210+
if CircularRegionOfInterest not in self.readable_objects:
211+
raise NeoReadWriteError(read_error)
206212

207213
def read_polygonregionofinterest(self, **kargs):
208-
assert PolygonRegionOfInterest in self.readable_objects, read_error
214+
if PolygonRegionOfInterest not in self.readable_objects:
215+
raise NeoReadWriteError(read_error)
209216

210217
def read_irregularlysampledsignal(self, **kargs):
211-
assert IrregularlySampledSignal in self.readable_objects, read_error
218+
if IrregularlySampledSignal not in self.readable_objects:
219+
raise NeoReadWriteError(read_error)
212220

213221
def read_channelview(self, **kargs):
214-
assert ChannelView in self.readable_objects, read_error
222+
if ChannelView not in self.readable_objects:
223+
raise NeoReadWriteError(read_error)
215224

216225
def read_event(self, **kargs):
217-
assert Event in self.readable_objects, read_error
226+
if Event not in self.readable_objects:
227+
raise NeoReadWriteError(read_error)
218228

219229
def read_epoch(self, **kargs):
220-
assert Epoch in self.readable_objects, read_error
230+
if Epoch not in self.readable_objects:
231+
raise NeoReadWriteError(read_error)
221232

222233
def read_group(self, **kargs):
223-
assert Group in self.readable_objects, read_error
234+
if Group not in self.readable_objects:
235+
raise NeoReadWriteError(read_error)
224236

225237
######## All individual write methods #######################
226238
def write_block(self, bl, **kargs):
227-
assert Block in self.writeable_objects, write_error
239+
if Block not in self.writeable_objects:
240+
raise NeoReadWriteError(write_error)
228241

229242
def write_segment(self, seg, **kargs):
230-
assert Segment in self.writeable_objects, write_error
243+
if Segment not in self.writeable_objects:
244+
raise NeoReadWriteError(write_error)
231245

232246
def write_spiketrain(self, sptr, **kargs):
233-
assert SpikeTrain in self.writeable_objects, write_error
247+
if SpikeTrain not in self.writeable_objects:
248+
raise NeoReadWriteError(write_error)
234249

235250
def write_analogsignal(self, anasig, **kargs):
236-
assert AnalogSignal in self.writeable_objects, write_error
251+
if AnalogSignal not in self.writeable_objects:
252+
raise NeoReadWriteError(write_error)
237253

238254
def write_imagesequence(self, imseq, **kargs):
239-
assert ImageSequence in self.writeable_objects, write_error
255+
if ImageSequence not in self.writeable_objects:
256+
raise NeoReadWriteError(write_error)
240257

241258
def write_rectangularregionofinterest(self, rectroi, **kargs):
242-
assert RectangularRegionOfInterest in self.writeable_objects, read_error
259+
if RectangularRegionOfInterest not in self.writeable_objects:
260+
raise NeoReadWriteError(write_error)
243261

244262
def write_circularregionofinterest(self, circroi, **kargs):
245-
assert CircularRegionOfInterest in self.writeable_objects, read_error
263+
if CircularRegionOfInterest not in self.writeable_objects:
264+
raise NeoReadWriteError(write_error)
246265

247266
def write_polygonregionofinterest(self, polyroi, **kargs):
248-
assert PolygonRegionOfInterest in self.writeable_objects, read_error
267+
if PolygonRegionOfInterest not in self.writeable_objects:
268+
raise NeoReadWriteError(write_error)
249269

250270
def write_irregularlysampledsignal(self, irsig, **kargs):
251-
assert IrregularlySampledSignal in self.writeable_objects, write_error
271+
if IrregularlySampledSignal not in self.writeable_objects:
272+
raise NeoReadWriteError(write_error)
252273

253274
def write_channelview(self, chv, **kargs):
254-
assert ChannelView in self.writeable_objects, write_error
275+
if ChannelView not in self.writeable_objects:
276+
raise NeoReadWriteError(write_error)
255277

256278
def write_event(self, ev, **kargs):
257-
assert Event in self.writeable_objects, write_error
279+
if Event not in self.writeable_objects:
280+
raise NeoReadWriteError(write_error)
258281

259282
def write_epoch(self, ep, **kargs):
260-
assert Epoch in self.writeable_objects, write_error
283+
if Epoch not in self.writeable_objects:
284+
raise NeoReadWriteError(write_error)
261285

262286
def write_group(self, group, **kargs):
263-
assert Group in self.writeable_objects, write_error
287+
if Group not in self.writeable_objects:
288+
raise NeoReadWriteError(write_error)

neo/io/brainwaref32io.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@
3232
import quantities as pq
3333

3434
# needed core neo modules
35-
from neo.core import Block, Group, Segment, SpikeTrain
35+
from neo.core import Block, Group, Segment, SpikeTrain, NeoReadWriteError
3636

3737
# need to subclass BaseIO
3838
from neo.io.baseio import BaseIO
@@ -127,7 +127,8 @@ def read_block(self, lazy=False, **kargs):
127127
Reads a block from the simple spike data file "fname" generated
128128
with BrainWare
129129
"""
130-
assert not lazy, "Do not support lazy"
130+
if lazy:
131+
raise NeoReadWriteError("This IO does not support lazy reading")
131132

132133
# there are no keyargs implemented to so far. If someone tries to pass
133134
# them they are expecting them to do something or making a mistake,

0 commit comments

Comments
 (0)