Special typing form to define literal types (a.k.a. value types). This form can be used to indicate to type checkers that the corresponding variable or function parameter has a value equivalent to the provided literal (or one of several literals):: def validate_simple(data: Any
(self, *parameters)
| 749 | @_TypedCacheSpecialForm |
| 750 | @_tp_cache(typed=True) |
| 751 | def Literal(self, *parameters): |
| 752 | """Special typing form to define literal types (a.k.a. value types). |
| 753 | |
| 754 | This form can be used to indicate to type checkers that the corresponding |
| 755 | variable or function parameter has a value equivalent to the provided |
| 756 | literal (or one of several literals):: |
| 757 | |
| 758 | def validate_simple(data: Any) -> Literal[True]: # always returns True |
| 759 | ... |
| 760 | |
| 761 | MODE = Literal['r', 'rb', 'w', 'wb'] |
| 762 | def open_helper(file: str, mode: MODE) -> str: |
| 763 | ... |
| 764 | |
| 765 | open_helper('/some/path', 'r') # Passes type check |
| 766 | open_helper('/other/path', 'typo') # Error in type checker |
| 767 | |
| 768 | Literal[...] cannot be subclassed. At runtime, an arbitrary value |
| 769 | is allowed as type argument to Literal[...], but type checkers may |
| 770 | impose restrictions. |
| 771 | """ |
| 772 | # There is no '_type_check' call because arguments to Literal[...] are |
| 773 | # values, not types. |
| 774 | parameters = _flatten_literal_params(parameters) |
| 775 | |
| 776 | try: |
| 777 | parameters = tuple(p for p, _ in _deduplicate(list(_value_and_type_iter(parameters)))) |
| 778 | except TypeError: # unhashable parameters |
| 779 | pass |
| 780 | |
| 781 | return _LiteralGenericAlias(self, parameters) |
| 782 | |
| 783 | |
| 784 | @_SpecialForm |