The typing module provides a function get_args which retrieves the arguments with which your Literal was initialized.

>>> from typing import Literal, get_args
>>> l = Literal['add', 'mul']
>>> get_args(l)
('add', 'mul')

However, I don't think you gain anything by using a Literal for what you propose.

Answer from tripleee on Stack Overflow
๐ŸŒ
Python
typing.python.org โ€บ en โ€บ latest โ€บ spec โ€บ literal.html
Literals โ€” typing documentation
This shortcut helps make writing signatures for functions that accept many different literals more ergonomic โ€” for example, functions like open(...): # Note: this is a simplification of the true type signature. _PathType = str | bytes | int @overload def open(path: _PathType, mode: Literal["r", "w", "a", "x", "r+", "w+", "a+", "x+"], ) -> IO[str]: ...
๐ŸŒ
Python
peps.python.org โ€บ pep-0586
PEP 586 โ€“ Literal Types | peps.python.org
March 14, 2019 - Note: String literal types like Literal["foo"] should subtype either bytes or unicode in the same way regular string literals do at runtime. For example, in Python 3, the type Literal["foo"] is equivalent to Literal[u"foo"], since "foo" is equivalent to u"foo" in Python 3.
Discussions

Getting the literal out of a python Literal type, at runtime? - Stack Overflow
@huyz I guess I didn't test at the time, and you seem to be right; neither Literal[lst] nor Literal[*lst] works for me in Python 3.8.2. 2021-01-12T05:34:54.12Z+00:00 ... Dynamic literal types are not allowed by the python standard python.org/dev/peps/pep-0586/โ€ฆ 2021-09-16T19:50:51.79Z+00:00 More on stackoverflow.com
๐ŸŒ stackoverflow.com
Inference on Literal Types - Typing - Discussions on Python.org
@erictraut and I have a disagreement on how objects declared as Literal should be propagated in collections. See pyright does not infer list of Literals, but mypy does ยท Issue #9491 ยท microsoft/pyright ยท GitHub I thought I would ask the community here their opinion, as my colleagues and ... More on discuss.python.org
๐ŸŒ discuss.python.org
2
November 22, 2024
Python type hints: How to use Literal with strings to conform with mypy? - Stack Overflow
I want to restrict the possible input arguments by using typing.Literal. The following code works just fine, however, mypy is complaining. from typing import Literal def literal_func(string_input: More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - Type hinting an object created by typing.Literal[] - Stack Overflow
I'm trying to create a function that goes through Unions and Literals and extracts their possible values. I'm trying to do that because I want to create a function that takes in a function and desc... More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
Python documentation
docs.python.org โ€บ 3 โ€บ library โ€บ typing.html
typing โ€” Support for type hints
1 month ago - To denote a tuple which could be of any length, and in which all elements are of the same type T, use the literal ellipsis ...: tuple[T, ...]. To denote an empty tuple, use tuple[()]. Using plain tuple as an annotation is equivalent to using ...
๐ŸŒ
Mypy
mypy.readthedocs.io โ€บ en โ€บ stable โ€บ literal_types.html
Literal types and Enums - mypy 1.19.1 documentation
If you do not provide an explicit type in the Final, the type of c becomes context-sensitive: mypy will basically try โ€œsubstitutingโ€ the original assigned value whenever itโ€™s used before performing type checking. This is why the revealed type of c is Literal[19]?: the question mark at the end reflects this context-sensitive nature. For example, mypy will type check the above program almost as if it were written like so:
๐ŸŒ
Adam Johnson
adamj.eu โ€บ tech โ€บ 2021 โ€บ 07 โ€บ 09 โ€บ python-type-hints-how-to-use-typing-literal
Python type hints: how to use typing.Literal - Adam Johnson
July 9, 2021 - To put it tautologically, type hints normally specify the types of variables. But when a variable can only contain a limited set of literal values, we can use typing.Literal for its type. This allows the type checker to make extra inferences, giving our code an increased level of safety.
๐ŸŒ
Medium
medium.com โ€บ data-science โ€บ python-type-hinting-with-literal-03c60ce42750
Python Type Hinting with Literal. More powerful than it seems: useโ€ฆ | by Marcin Kozak | TDS Archive | Medium
November 28, 2023 - PYTHON PROGRAMMING Python Type Hinting with Literal More powerful than it seems: use typing.Literal to create literal types Iโ€™ll admit it: I wasnโ€™t always a fan of typing.Literal, a form of โ€ฆ
Find elsewhere
Top answer
1 of 3
78

The typing module provides a function get_args which retrieves the arguments with which your Literal was initialized.

>>> from typing import Literal, get_args
>>> l = Literal['add', 'mul']
>>> get_args(l)
('add', 'mul')

However, I don't think you gain anything by using a Literal for what you propose.

2 of 3
6

I'm working with lots of sets of different characters and character sequences and ended up here.

If you're using type aliases defined using the type statement, get_args doesn't work directly. And a Union of Literals is messy, so the below is what I ended up with:

from collections.abc import Sequence, Iterator
from typing import Literal, get_args, TypeAliasType, cast

def get_literal_vals(alias: TypeAliasType) -> frozenset:
    def val(alias: TypeAliasType):
        return alias.__value__
    def args(alias: TypeAliasType):
        return get_args(val(alias))
    def resolveT -> Iterator[T]:
        if isinstance(alias, TypeAliasType):
            for val in resolve(args(alias)):
                yield from resolve(val)
            return
        if isinstance(alias, tuple):
            t_seq = cast(Sequence[T], alias)
            for element in t_seq:
                yield from resolve(element)
            return
        yield alias
    return frozenset(resolve(alias))

type Doubles = Literal["ab", "de", "gh"]
type Triples = Literal["abc", "def", "ghi"]
type DT = Doubles | Triples
dt_set: frozenset[DT] = get_literal_vals(DT)

This has some type checking issues depending on how strict your type checker is but works in practice:

>>> type Triples = Literal["abc", "def", "ghi"]
>>> get_literal_vals(Triples)
frozenset({'def', 'abc', 'ghi'})
>>> type Doubles = Literal["ab", "de", "gh"]
>>> get_literal_vals(Doubles)
frozenset({'gh', 'de', 'ab'})
>>> type DT = Doubles | Triples
>>> get_literal_vals(DT)
frozenset({'ghi', 'de', 'ab', 'abc', 'gh', 'def'})

An interesting side effect of this is that dynamic user input string values can be constrained to a set of specific literal values within conditional branches.

def foo(bar: str):
    if bar in dt_set:
        # bar is considered a literal value in DT
        # by some type checkers.
        pass
    # bar is an unconstrained string value
    # outside of the conditional branch.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ dynamic-testing-of-values-against-python-literal-types
Dynamic Testing of Values Against Python Literal Types - GeeksforGeeks
July 23, 2025 - # code from typing import Literal def get_fruit(fruit: Literal['apple', 'banana', 'cherry']) -> str: return fruit ยท This function will only accept 'apple', 'banana', or 'cherry' as valid arguments. Any other value will result in a type error if checked by a type checker like mypy. To dynamically test if a value conforms to a Python Literal type, you can use the typing_extensions module, which provides compatibility with older versions of Python (prior to 3.8) and allows you to define and check for literal types using Literal.
๐ŸŒ
Python.org
discuss.python.org โ€บ typing
Inference on Literal Types - Typing - Discussions on Python.org
November 22, 2024 - @erictraut and I have a disagreement on how objects declared as Literal should be propagated in collections. See pyright does not infer list of Literals, but mypy does ยท Issue #9491 ยท microsoft/pyright ยท GitHub I thought I would ask the community here their opinion, as my colleagues and ...
๐ŸŒ
TestDriven.io
testdriven.io โ€บ tips โ€บ c61d55d8-caa7-4ab4-b611-7356bddc0181
Tips and Tricks - Python type hints - typing.Literal | TestDriven.io
from typing import Literal STATUS = Literal["ACTIVE", "DISABLED"] class User: def __init__(self, username: str, status: STATUS): self.username = username self.status = status user = User("[email protected]", "CREATED") """ mypy example.py example.py:12: error: Argument 2 to "User" has incompatible type "Literal['CREATED']"; expected "Union[Literal['ACTIVE'], Literal['DISABLED']]" Found 1 error in 1 file (checked 1 source file) """
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ literals-in-python
Literals in Python - GeeksforGeeks
July 15, 2025 - Literals in Python are fixed values written directly in the code that represent constant data. They provide a way to store numbers, text, or other essential information that does not change during program execution.
๐ŸŒ
Turingtaco
turingtaco.com โ€บ exploring-literal-types-for-robust-python-programming
Exploring Literal Types for Robust Python Programming
December 7, 2024 - Literal Types enhance Python type-checking capabilities, allowing us to differentiate between values written directly in our programs and values from outside the program as input; for this distinction, the source of the input data is not essential.
๐ŸŒ
YouTube
youtube.com โ€บ watch
Python Has A "Literal" Type That I've NEVER Seen Before - YouTube
This import from the typing module is incredibly useful when you need to check value types. Sorry about the bad word play in the title.โ–ถ Become job-ready wit...
Published ย  August 3, 2023
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ difference between "variable" and "literal"
r/learnpython on Reddit: Difference between "Variable" and "Literal"
January 8, 2022 -

My understanding is that Literal objects are the basic dataforms provided by a Programming language, although they all are condensed as binary data string; Literals don't have names, they are literally the data they are representing. Various types of Literals available for programmers to use, is bound by what the programming language is providing. Looking at this in a lower level (CPU and memory level), literals represent the entire binary memory sequence where the corresponding literal's value or data is stored.
Variables, On the other hand, are programming constructs using which one can refer to a literal, by pointing to its memory slice (corresponding starting point in the memory and the size of the literal).

I am unsure, if my above understanding is accurate with the true meaning of the terms Literal and Variable. So, please share your ramifications on my above understanding, and add if I have missed something.

Top answer
1 of 2
8
No, sorry, you are mostly wrong. You are confusing "literal" with "primitive". Technically python has neither variables nor primitives. But python 'names' are very commonly called 'variables'. A literal just means data that's typed directly into the source code. It can be identical to data that's typed in, but if it's hardcoded in the code it's called a literal. You can (and we often do) assign a literal to a name. spam = 42 Here we assign the literal 42 to the name (variable) spam. if int(input('Type 42: ')) == 42: Here we compare some inputted value to the literal value.
2 of 2
1
In the source code for many programming languages "Bins are collected on Wednesday" would be a literal string. Literal in the English sense in that there's no abstraction or proxy here as that is what was actually written. Similarly "Bins are collected tomorrow" is also a literal string from a programming point of view as that is, again, what is actually written in the source code. But logically, in English terms, there is a variable element here. tomorrow can be any day. In Python names are used to reference Python objects that reside somewhere in memory. In the reference implementation of Python, some simple objects, like integers from -5 to 256, are predefined (their binary representation is built into the compiled version of CPython). When CPython compiles the source code of a Python file for execution by the Python interpreter in the Python Virtual Machine, the compiler will replace any literal representations of such small integers in the source code with a reference to the corresponding binary object. In the case of the string mentioned earlier, a new object will be created to store that literal string as a series of unicode binary sequences. Most programming languages will not recognise the variable element pertaining to tomorrow. We have to code such variable elements explicitly. Both integers and strings, whether predefined or leading to objects being created, are Python primitives in that they are the building blocks of the language. Floating point numbers, and complex numbers are also primitives. However, when I write the expression 2.5 * 3 + 4j in my source code literally the compiler will recognise the expression contains two primitives, namely one floating point number and one complex number, neither of which are predefined objects. If it has some optimisation routines, it might just do the calculation and replace both with a reference to the resulting object but otherwise it would create two binary object representations and replace the literal human readable number representations with the appropriate memory references in the Python byte code ready for the interpreter. Clearly if the literal source code read, size * 3 + 4j then the compiler would recognise the literal text in the source code size is a name, likely being used as a variable that should already be referencing an object. Again, the compiler would replace the literal complex number with an object memory reference but for the name, the interpreter would be left to look up the current object at run time as Python is an interpreted language so there's a limit to how much work the compiler can do. Back to the beginning. from datetime import datetime today = datetime.today().strftime("%A") if today == 'Wednesday': when = 'today' elif today == 'Tuesday': when = 'tomorrow' else: when = 'on Wednesday' print('The bins will be collected', when) All of the text in quotes are string literals that will be turned into str objects, str being a Python primitive. The objects will be binary representations using unicode encoding. today and when are variable names. datetime is the name of an imported object providing date and time functionality. E&OE as typed this on my mobile whilst not fully awake.
๐ŸŒ
GitHub
github.com โ€บ python โ€บ mypy โ€บ issues โ€บ 9230
Looping through literals not typed correctly ยท Issue #9230 ยท python/mypy
July 29, 2020 - from typing import TypedDict class FooDict(TypedDict): foo: int bar: int foo = FooDict(foo=3, bar=3) print(foo["foo"]) # Works print(foo["bar"]) # Works reveal_type(("foo", "bar")) # Revealed type is 'Tuple[Literal['foo']?, Literal['bar']?]' for key in ("foo", "bar"): reveal_type(key) # Revealed type is 'builtins.str' print(foo[key]) # TypedDict key must be a string literal; expected one of ('foo', 'bar')
Author ย  rggjan
๐ŸŒ
GitHub
github.com โ€บ python โ€บ mypy โ€บ issues โ€บ 16813
Enhanced Literal Detection: Allow string type narrowing to literals ยท Issue #16813 ยท python/mypy
January 24, 2024 - Feature It would be great if mypy could detect and type narrow strings to Literals if this is statically detectable. I.e. if accessing TypedDict or Enum values Pitch from typing import TypedDict class Part(TypedDict, total=False): a: int...
Author ย  CarliJoy