How to properly function annotate / type hint a list of strings

前端 未结 2 1326
天命终不由人
天命终不由人 2021-01-05 00:24

I am trying to figure out how to properly function annotate or type hint a list of strings. For example, if I had a function like this:

def send_email(self,         


        
相关标签:
2条回答
  • 2021-01-05 00:51

    Python 3.4 doesn't specify a format for its function annotations, it merely provides a mechanism that allows you to use any expression as the annotation. How the annotations are interpreted is up to you and the libraries you use.

    Python 3.5 will standardize the way function annotations are used for type hinting, as documented in PEP 484. To annotate a list of strings, you would use List[str], where List is imported from the typing module. You can also use Sequence[str] if your function accepts any list-like sequence, or Iterable[str] for any iterable.

    0 讨论(0)
  • 2021-01-05 00:58

    You need to import

    from typing import List
    List[str]
    

    Note the capital L.

    In python 3.9+ the lower case l also supports generics.

    You might want to consider something more specific. Why is to_adress a Str, but from_Adress is a List[Str]? Maybe a

    Adress = typing.NewType("Adress")
    

    is helpful.

    0 讨论(0)
提交回复
热议问题