Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

List types can 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading