|
| 1 | +# -*- coding: utf-8 |
| 2 | +""" |
| 3 | +Module containing general utility functions. |
| 4 | +""" |
| 5 | + |
| 6 | + |
| 7 | +def format_cardinality(in_val): |
| 8 | + """ |
| 9 | + Checks an input value and formats it towards a custom tuple format |
| 10 | + used in odml Section, Property and Values cardinality. |
| 11 | +
|
| 12 | + The following cases are supported: |
| 13 | + (n, n) - default, no restriction |
| 14 | + (d, n) - minimally d entries, no maximum |
| 15 | + (n, d) - maximally d entries, no minimum |
| 16 | + (d, d) - minimally d entries, maximally d entries |
| 17 | +
|
| 18 | + Only positive integers are supported. 'None' is used to denote |
| 19 | + no restrictions on a maximum or minimum. |
| 20 | +
|
| 21 | + :param in_val: Can either be 'None', a positive integer, which will set |
| 22 | + the maximum or an integer 2-tuple of the format '(min, max)'. |
| 23 | +
|
| 24 | + :returns: None or the value as tuple. A ValueError is raised, if the |
| 25 | + provided value was not in an acceptable format. |
| 26 | + """ |
| 27 | + exc_msg = "Can only assign positive single int or int-tuples of the format '(min, max)'" |
| 28 | + |
| 29 | + # Empty values reset the cardinality to None. |
| 30 | + if not in_val or in_val == (None, None): |
| 31 | + return None |
| 32 | + |
| 33 | + # Providing a single integer sets the maximum value in a tuple. |
| 34 | + if isinstance(in_val, int) and in_val > 0: |
| 35 | + return None, in_val |
| 36 | + |
| 37 | + # Only integer 2-tuples of the format '(min, max)' are supported to set the cardinality |
| 38 | + if isinstance(in_val, tuple) and len(in_val) == 2: |
| 39 | + v_min = in_val[0] |
| 40 | + v_max = in_val[1] |
| 41 | + |
| 42 | + min_int = isinstance(v_min, int) and v_min >= 0 |
| 43 | + max_int = isinstance(v_max, int) and v_max >= 0 |
| 44 | + |
| 45 | + if max_int and min_int and v_max > v_min: |
| 46 | + return v_min, v_max |
| 47 | + |
| 48 | + if max_int and not v_min: |
| 49 | + return None, v_max |
| 50 | + |
| 51 | + if min_int and not v_max: |
| 52 | + return v_min, None |
| 53 | + |
| 54 | + # Use helpful exception message in the following case: |
| 55 | + if max_int and min_int and v_max < v_min: |
| 56 | + exc_msg = "Minimum larger than maximum (min=%s, max=%s)" % (v_min, v_max) |
| 57 | + |
| 58 | + raise ValueError(exc_msg) |
0 commit comments