7

Given this function:

def array_returner():
    return ["hello", "there"]

How would I typehint that this function returns an array of strings, without importing List (and using the List[str] syntax)?

Newbyte
  • 2,421
  • 5
  • 22
  • 45
  • 1
    Duplicate: [How to properly function annotate / type hint a list of strings](https://stackoverflow.com/questions/31905597/how-to-properly-function-annotate-type-hint-a-list-of-strings) – Georgy Dec 08 '19 at 20:03
  • Also: [Type hinting a list of a specified type](https://stackoverflow.com/q/24853923/7851470) – Georgy Dec 08 '19 at 20:06
  • @Georgy These questions address Lists, not arrays. I don't want to import List. (and `list[str]` evidently does not work) – Newbyte Dec 08 '19 at 20:25
  • I think you need exactly the list, as your example function returns a list, [not an "array"](https://stackoverflow.com/questions/1514553/how-to-declare-an-array-in-python). Even if it's not the case, I don't get why you want to avoid using `List[str]`, and at the same time you accepted an answer that proposed it. Could you clarify, please? – Georgy Dec 08 '19 at 20:35
  • Another duplicate: [How can I create a type hint that my returned list contains strings?](https://stackoverflow.com/q/37386499/7851470) – Georgy Dec 08 '19 at 20:43
  • @Georgy You are right, I misunderstood (however `[str]` works just fine?). Regarding my accepted answer it proposed both `List[str]` and `[str]`. As for why I would want to avoid importing List — mainly that I see no reason to import it if there is a syntax that lets me do without it. Is there any reason to use it (rather than this syntax)? I realise this might be somewhat off-topic though. – Newbyte Dec 08 '19 at 20:44
  • Using `[str]` is not a proper way to type hint a list of strings. You can check it, for example, [here](https://mypy-play.net/). It will give you the following error: "*Bracketed expression "[...]" is not valid as a type*... *Did you mean "List[...]"?*". I guess it's possible that your IDE can accept `[str]`, but I don't know how well it will work. I suggest not using this syntax, as it is [not documented](https://www.python.org/dev/peps/pep-0484/). – Georgy Dec 08 '19 at 20:59
  • @Georgy Regarding how well it works, I get not warnings in Python 3.7.5. But, considering that it is undocumented — fair, I'll admit defeat. Thank you. – Newbyte Dec 08 '19 at 21:08

2 Answers2

13

This is what you're looking for:

from typing import List

def array_returner() -> List[str]:
    return ["hello", "there"]
Ian
  • 3,605
  • 4
  • 31
  • 66
10

You can do like this

  • def array_returner() -> [str]:
  • def array_returner() -> List[str]: (from typing import List)
azro
  • 53,056
  • 7
  • 34
  • 70