Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3.12: Correct typing for list[list[int,str,list[list[str]]]]?

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]]:

screenshot

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?

like image 292
Cow Avatar asked Nov 05 '25 08:11

Cow


1 Answers

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.

like image 183
jsbueno Avatar answered Nov 07 '25 00:11

jsbueno