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)
| 772 | @_TypedCacheSpecialForm |
| 773 | @_tp_cache(typed=True) |
| 774 | def Literal(self, *parameters): |
| 775 | """Special typing form to define literal types (a.k.a. value types). |
| 776 | |
| 777 | This form can be used to indicate to type checkers that the corresponding |
| 778 | variable or function parameter has a value equivalent to the provided |
| 779 | literal (or one of several literals):: |
| 780 | |
| 781 | def validate_simple(data: Any) -> Literal[True]: # always returns True |
| 782 | ... |
| 783 | |
| 784 | MODE = Literal['r', 'rb', 'w', 'wb'] |
| 785 | def open_helper(file: str, mode: MODE) -> str: |
| 786 | ... |
| 787 | |
| 788 | open_helper('/some/path', 'r') # Passes type check |
| 789 | open_helper('/other/path', 'typo') # Error in type checker |
| 790 | |
| 791 | Literal[...] cannot be subclassed. At runtime, an arbitrary value |
| 792 | is allowed as type argument to Literal[...], but type checkers may |
| 793 | impose restrictions. |
| 794 | """ |
| 795 | # There is no '_type_check' call because arguments to Literal[...] are |
| 796 | # values, not types. |
| 797 | parameters = _flatten_literal_params(parameters) |
| 798 | |
| 799 | try: |
| 800 | parameters = tuple(p for p, _ in _deduplicate(list(_value_and_type_iter(parameters)))) |
| 801 | except TypeError: # unhashable parameters |
| 802 | pass |
| 803 | |
| 804 | return _LiteralGenericAlias(self, parameters) |
| 805 | |
| 806 | |
| 807 | @_SpecialForm |
searching dependent graphs…