nineml.utility.expect_single

nineml.utility.expect_single(lst, error_func=None)[source]

Retrieve a single element from an iterable.

This function tests whether an iterable contains just a single element and if so returns that element. Otherwise it raises an Exception.

Parameters:
  • lst – An iterable
  • error_func – An exception object or a callable. error_func will be raised or called in case there is not exactly one element in lst. If error_func is None, a NineMLRuntimeError exception will be raised.
Return type:

the element in the list, lst[0], provided len(lst)==1

>>> expect_single( ['hello'] )
'hello'
>>> expect_single( [1] )
1
>>> expect_single( [] ) 
NineMLRuntimeError: expect_single() recieved an iterable of length: 0
>>> expect_single( [None,None] ) 
NineMLRuntimeError: expect_single() recieved an iterable of length: 2
>>> expect_single( [], lambda: raise_exception( RuntimeError('Aggh') ) 
RuntimeError: Aggh
>>> #Slightly more tersly:
>>> expect_single( [], RuntimeError('Aggh') ) 
RuntimeError: Aggh