2021年4月24日 星期六

[ Python 常見問題 ] Type hint for a function that returns only a specific set of values

 Source From Here

Question
I have a function that can only return a, b or c, all of them are of type T. And I want to include this fact in the signature because of the special meaning they carry in the context of the function. How do I do that? Currently, I use this

  1. def fun(...) -> "a or b or c":  
  2.     #briefly explain the meaning of a, b and c in its docstring  
Is that the correct one? I know that I can do this
  1. def fun(...) -> T:  
  2.     #briefly explain the meaning of a, b and c in its docstring  
but as I said I want to express in the signature that the function only returns those specific values.

HowTo
You can do that with literal types.
  1. from typing_extensions import Literal  
  2. # from typing import Literal  # Python 3.8 or higher  
  3.   
  4. def fun(b: int) -> Literal["a""b""c"]:  
  5.     if b == 0:  
  6.         return "a"  
  7.     if b == 1:  
  8.         return "b"  
  9.     return "d"  
mypy is able to detect the return "d" as a invalid statement:
  1. error: Incompatible return value type (got "Literal['d']",  
  2. expected "Union[Literal['a'], Literal['b'], Literal['c']]")  
Python 3.8
Thanks to the PEP 586, the Literal is already included by default in the Python 3.8 typing module.

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...