Check the value of a parameter against a list of valid options. Return the value if it is valid, otherwise raise a ValueError with a readable error message. Parameters ---------- parameter : str The name of the parameter to check. This is used in the error message.
(parameter, value, allowed_values, extra="")
| 887 | |
| 888 | |
| 889 | def _check_option(parameter, value, allowed_values, extra=""): |
| 890 | """Check the value of a parameter against a list of valid options. |
| 891 | |
| 892 | Return the value if it is valid, otherwise raise a ValueError with a |
| 893 | readable error message. |
| 894 | |
| 895 | Parameters |
| 896 | ---------- |
| 897 | parameter : str |
| 898 | The name of the parameter to check. This is used in the error message. |
| 899 | value : any type |
| 900 | The value of the parameter to check. |
| 901 | allowed_values : list |
| 902 | The list of allowed values for the parameter. |
| 903 | extra : str |
| 904 | Extra string to append to the invalid value sentence, e.g. |
| 905 | "when using ico mode". |
| 906 | |
| 907 | Raises |
| 908 | ------ |
| 909 | ValueError |
| 910 | When the value of the parameter is not one of the valid options. |
| 911 | |
| 912 | Returns |
| 913 | ------- |
| 914 | value : any type |
| 915 | The value if it is valid. |
| 916 | """ |
| 917 | if value in allowed_values: |
| 918 | return value |
| 919 | |
| 920 | # Prepare a nice error message for the user |
| 921 | extra = f" {extra}" if extra else extra |
| 922 | msg = ( |
| 923 | "Invalid value for the '{parameter}' parameter{extra}. " |
| 924 | "{options}, but got {value!r} instead." |
| 925 | ) |
| 926 | allowed_values = list(allowed_values) # e.g., if a dict was given |
| 927 | if len(allowed_values) == 1: |
| 928 | options = f"The only allowed value is {repr(allowed_values[0])}" |
| 929 | else: |
| 930 | options = "Allowed values are " |
| 931 | if len(allowed_values) == 2: |
| 932 | options += " and ".join(repr(v) for v in allowed_values) |
| 933 | else: |
| 934 | options += ", ".join(repr(v) for v in allowed_values[:-1]) |
| 935 | options += f", and {repr(allowed_values[-1])}" |
| 936 | raise ValueError( |
| 937 | msg.format(parameter=parameter, options=options, value=value, extra=extra) |
| 938 | ) |
| 939 | |
| 940 | |
| 941 | def _check_all_same_channel_names(instances): |
no outgoing calls