Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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, from_address: str, to_addresses: list[str]):     pass 

to_addresses should be a list of strings. But when I try to use that annotation I get the following error in my Python 3.4.3 interpreter:

TypeError: 'type' object is not subscriptable

I am positive the list[str] is causing the issue, because if I change it to str the error goes away, but that doesn't properly reflect my intentions for the parameter.

like image 502
gnychis Avatar asked Aug 09 '15 15:08

gnychis


People also ask

What is the correct syntax for Annotate function?

Function Annotationsdef func(arg: arg_type, optarg: arg_type = default) -> return_type: ... For arguments, the syntax is argument: annotation , while the return type is annotated using -> annotation . Note that the annotation must be a valid Python expression.

How do you annotate a type in Python?

To annotate return value type, add -> immediately after closing the parameter parentheses, just before the function definition colon( : ): def announcement(language: str, version: float) -> str: ... The function now has type hints showing that it receives str and float arguments, and returns str .

Should you use type annotations Python?

Type hints work best in modern Pythons. Annotations were introduced in Python 3.0, and it's possible to use type comments in Python 2.7. Still, improvements like variable annotations and postponed evaluation of type hints mean that you'll have a better experience doing type checks using Python 3.6 or even Python 3.7.

What is a type hint?

Introduction to Python type hints It means that you need to declare types of variables, parameters, and return values of a function upfront. The predefined types allow the compilers to check the code before compiling and running the program.


1 Answers

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 standardizes the way function annotations are used for type hinting, as documented in PEP 484. To annotate a list of strings, you 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.

Starting with Python 3.9, you can use list[str] as a type annotation, which doesn't require importing anything.

like image 156
interjay Avatar answered Oct 01 '22 01:10

interjay