Use 'typing' library to hint co-developers reading the code to understand what datatype will a function return.
To hint input types
Example 1
def __init__(self, name: str, price: float, store_id: int):
self.name = name
self.price = price
self.store_id = store_id
Example 2
@classmethod
def find_by_name(cls, name: str) -> "ItemModel": # classmethod to search item in database by name
return cls.query.filter_by(name=name).first()Example 3
@classmethod
def find_by_id(cls, _id: int) -> "UserModel": # classmethod to search store in database by id
return cls.query.filter_by(id=_id).first()
adding ":str" or ":int" or ":float" in front of the parameter only tells other developers about what is the expected input. It does not actually participate in giving errors when user actually does that.
To hint return types
This requires to import typing library
from typing import Dict, List, Union
When indicating the return type to be Dict
Example 1
Create a new variable that will explain how this particular Dict datatype is designed. Which means, what datatype will be the key and what datatype will be the value.
ItemJSON = Dict[str, Union[int, str, float]]
Then use it in the function to indicate that this is the data type the function would return
def json(self) -> ItemJSON:
return {"id": self.id, "name": self.name, "price": self.price, "store_id": self.store_id}
Example 2
Use previously defined variable for defining the 'Dict' into a new variable to define a new 'Dict', which includes a 'List' of previously defined 'Dict'
StoreJSON = Dict[str, Union[int, str, List[ItemJSON]]]
Then use it in the function to indicate that this is the data type the function would return
def json(self) -> StoreJSON:
return {"id": self.id, "name": self.name, "items": [item.json() for item in self.items.all()]}
When indicating the return type to be a class
Example 1
To indicate that the returning object is a class
@classmethod
def find_by_name(cls, name: str) -> "ItemModel": # classmethod to search in database by name
return cls.query.filter_by(name=name).first()
Example 2
And there could be a list of objects of a class type
@classmethod
def find_all(cls) -> List["ItemModel"]:
return cls.query.all()
Comments
Post a Comment