Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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...

like image 370
koalaok Avatar asked Oct 03 '18 08:10

koalaok


People also ask

How do you define return type in Python?

A return statement is used to end the execution of the function call and “returns” the result (value of the expression following the return keyword) to the caller. The statements after the return statements are not executed. If the return statement is without any expression, then the special value None is returned.

How do you return a list element in Python?

A Python function can return any object such as a list. To return a list, first create the list object within the function body, assign it to a variable your_list , and return it to the caller of the function using the keyword operation “ return your_list “.

Do you have to specify return type in Python?

Yes it is. In Python a function doesn't always have to return a variable of the same type (although your code will be more readable if your functions do always return the same type). That means that you can't specify a single return type for the function.

What does type () do in Python?

Syntax of the Python type() function The type() function is used to get the type of an object. When a single argument is passed to the type() function, it returns the type of the object. Its value is the same as the object.


1 Answers

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.

like image 118
Ramazan Polat Avatar answered Sep 25 '22 01:09

Ramazan Polat