I have a list of strings:
strings = ['a','b','c']
I want to declare a Union
of Literal
types of all the possible ordered pairs of the list. Hardcoded, this would look like:
CustomType = Literal[
'ab', 'ac', 'aa',
'ba', 'bb', 'bc',
'ca', 'cb', 'cc'
]
How could I define CustomType
dynamically such that I don't have to manually put each combination?
I'm thinking something along the lines of:
CustomType = Literal[*permutations(strings)]
but that gives me the error:
Unpack operator in subscript requires Python 3.11 or newer
Pylance
Unpacked arguments cannot be used in type argument lists
Pylance
The objective motivating this question is to have Pylance detect if I try passing a string that is not an element of that set.
def f(string: CustomType):
...
f('foo') # Pylance will complain
f('ba') # Pylance will permit
source https://stackoverflow.com/questions/74075558/dynamically-define-a-union-of-literal-permutations-in-python
Comments
Post a Comment