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

koalaok picture koalaok · Oct 3, 2018 · Viewed 11.4k times · Source

Let's say I have a method like the following

def validate(self, item:dict, attrs:dict)-> list:

If I want to be more specific and tell that my return type is a list of ValidationMessages?

How should I / Can I achieve that?

( I would check off the mark as a duplicate, since this is not about extending a list or flattening) I'm asking about how to be more specific on identifying the return type of a method....

Answer

Ramazan Polat picture Ramazan Polat · Oct 3, 2018

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.