Python annotation for list of specific types

242 views Asked by At

I would like to annotate a list of a str and an int, e.g.:

    state = ['mystring', 4]

I can't use tuple, becuase I have to change the integer without changing the reference of the state (it is passed to functions, which also have to modify it). Note that this is a typical tuple case, just since int is immutable in python, ...

def myfunc(state: ?) -> bool:
    ...
    state[1] += 1
    ...
    return success

What is the best way to annotate it? I tried

    state: list[str, int]

(similarly to a tuple) which compiles well, but mypy throws an exception, that list expects only a single argument. I can also use

    state: list[str|int]

But this is a "different type" for different use cases.

1

There are 1 answers

0
FERcsI On

Based on @MisterMiyagi-s comment, the answer is, that we shouldn't use list as an alternative to tuple, just because we need to modifiy the values. List should be a sequence of objects of the same type (or more types).

The proper solution could be:

from dataclasses import dataclass

@dataclass
class State:
    text: str
    pos: int
    
...

state = State('mystring', 4)

...

def myfunc(state: State) -> bool:
    ...
    state.pos += 1
    ...
    return success