How to specify method return type list of (what) in Python?

With Python 3.6, the built-in typing package will do the job.

from typing import List

def validate(self, item:dict, attrs:dict)-> List[str]:
    ...

The notation is a bit weird, since it uses brackets but works out pretty well.

Edit: With the new 3.9 version of Python, you can annotate types without importing from the typing module. The only difference is that you use real type names instead of defined types in the typing module.

def validate(self, item:dict, attrs:dict)-> list[str]:
    ...

NOTE: Type hints are just hints that help IDE. Those types are not enforced. You can add a hint for a variable as str and set an int to it like this:


a:str="variable hinted as str"
a = 5  # See, we can set an int 

Your IDE will warn you but you will still be able to run the code. Because those are just hints. Python is not a type strict language. Instead, it employs dynamic typing.

Leave a Comment