Type Hinting List of Strings [duplicate]
Asked Answered
J

1

9

In python, if I am writing a function, is this the best way to type hint a list of strings:

def sample_def(var:list[str]):

Jilljillana answered 16/2, 2022 at 20:6 Comment(0)
L
16

I would use the typing module

from typing import List

def foo(bar: List[str]):
    pass

The reason is typing contains so many type hints and the ability to create your own, specify callables, etc. Definitely check it out.

Edit:
I guess as of Python 3.9 typing is deprecated (RIP). Instead it looks like you can use collections.abc.*. So you can do this if you're on Python 3.9+:

from collections.abc import Iterable

def foo(bar: Iterable[str]):
    pass

You can take a look at https://docs.python.org/3/library/collections.abc.html for a list of ABCs that might fit your need. For instance, it might make more sense to specify Sequence[str] depending on your needs of that function.

Levey answered 16/2, 2022 at 20:10 Comment(4)
In my opinion, if you recommend something despite it being deprecated, you should more clearly say why.Galactic
Hmm, what do you have against the way they show in the question?Galactic
@KellyBundy it doesn't have any backwards compatibility with things like Python 3.7 so it seems like a bad idea to me.Levey
That might be an argument against it, yes, though not in the 3.9+ part of your answer. Also, 3.9 is 500 days old, so probably many people are using it (or 3.10) by now :-). And you can already use in 3.7, with from __future__ import annotations.Galactic

© 2022 - 2025 — McMap. All rights reserved.