I have a list of users, that I would like to type correctly, but I'm not able to find an answer explaining how to do this.
The list looks like this:
listofusers = [[167, 'john', 'John Fresno', [[538, 'Privileged'], [529, 'User']]]]
I tried doing like this:
def test(listofusers: list[list[str,list[list[str]]]]) -> None:
...
But VS Code only shows typing for: list[list[str]]:

I also tried using Union, like this:
listofusers: list[list[Union[int,str,list[list[str]]]]]
But again, this doesn't seems to work.
Can someone shed a light over this?
List types can't be specified on a per-position basis: the recommended thing to have with lists under typing, and also, common sense, is for lists to be homogeneous: they should contain a single element type. If one needs to group data with different semantics (even if they would be of the same type) in a sequence, a tuple should be preferred.
So, if you really can't, or are unwilling to, create a class for each element in your outer list, which would correctly encapsulate the information, with fields and such, this data:
listofusers = [(167, 'john', 'John Fresno', [(538, 'Privileged'), (529, 'User')],)]
Could be typed as:
list[tuple[int, str, str, list[tuple[int, str]]]]
But this is really "double plus ungood" if you are worried with a large system for long term maintainability.
You should obviously have a User model with four fields, the fourth being a sequence of a Permission model.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With