|
25 | 25 | def set_if_not_none(property_name, property, export): |
26 | 26 | if property is not None: |
27 | 27 | export[property_name] = property.to_dict() |
| 28 | + |
| 29 | +def check_type(obj, acceptable_types, is_list=False, may_be_none=False): |
| 30 | + """Object is an instance of one of the acceptable types or None. |
| 31 | +
|
| 32 | + Args: |
| 33 | + obj: The object to be inspected. |
| 34 | + acceptable_types: A type or tuple of acceptable types. |
| 35 | + is_list(bool): Whether or not we expect a list of objects of acceptable |
| 36 | + type |
| 37 | + may_be_none(bool): Whether or not the object may be None. |
| 38 | +
|
| 39 | + Raises: |
| 40 | + TypeError: If the object is None and may_be_none=False, or if the |
| 41 | + object is not an instance of one of the acceptable types. |
| 42 | +
|
| 43 | + """ |
| 44 | + error_message = None |
| 45 | + if not isinstance(acceptable_types, tuple): |
| 46 | + acceptable_types = (acceptable_types,) |
| 47 | + |
| 48 | + if may_be_none and obj is None: |
| 49 | + pass |
| 50 | + elif is_list: |
| 51 | + # Check that all objects in that list are of the required type |
| 52 | + if not isinstance(obj, list): |
| 53 | + error_message = ( |
| 54 | + "We were expecting to receive a list of one of the following " |
| 55 | + "types: {types}{none}; but instead we received {o} which is a " |
| 56 | + "{o_type}.".format( |
| 57 | + types=", ".join([repr(t.__name__) for t in acceptable_types]), |
| 58 | + none="or 'None'" if may_be_none else "", |
| 59 | + o=obj, |
| 60 | + o_type=repr(type(obj).__name__) |
| 61 | + ) |
| 62 | + ) |
| 63 | + else: |
| 64 | + for o in obj: |
| 65 | + if not isinstance(o, acceptable_types): |
| 66 | + error_message = ( |
| 67 | + "We were expecting to receive an instance of one of the following " |
| 68 | + "types: {types}{none}; but instead we received {o} which is a " |
| 69 | + "{o_type}.".format( |
| 70 | + types=", ".join([repr(t.__name__) for t in acceptable_types]), |
| 71 | + none="or 'None'" if may_be_none else "", |
| 72 | + o=o, |
| 73 | + o_type=repr(type(o).__name__) |
| 74 | + ) |
| 75 | + ) |
| 76 | + elif isinstance(obj, acceptable_types): |
| 77 | + pass |
| 78 | + else: |
| 79 | + # Object is something else. |
| 80 | + error_message = ( |
| 81 | + "We were expecting to receive an instance of one of the following " |
| 82 | + "types: {types}{none}; but instead we received {o} which is a " |
| 83 | + "{o_type}.".format( |
| 84 | + types=", ".join([repr(t.__name__) for t in acceptable_types]), |
| 85 | + none="or 'None'" if may_be_none else "", |
| 86 | + o=obj, |
| 87 | + o_type=repr(type(obj).__name__) |
| 88 | + ) |
| 89 | + ) |
| 90 | + if error_message is not None: |
| 91 | + raise TypeError(error_message) |
0 commit comments