2021年8月1日 星期日

[ Python 常見問題 ] How do I type hint a method with the type of the enclosing class?

 Source From Here

Question
I have the following code in python 3:
  1. class Position:  
  2.   
  3.     def __init__(self, x: int, y: int):  
  4.         self.x = x  
  5.         self.y = y  
  6.   
  7.     def __add__(self, other: Position) -> Position:  
  8.         return Position(self.x + other.x, self.y + other.y)  
But the return type hinting def __add__(self, other: Position) -> Position will fail.

HowTo
If you are using Python 3.10 or later, it just works. As of today (2019), in 3.7+ you must turn this feature on using a future statement (from __future__ import annotations). In Python 3.6 or below, use a string.

I guess you got this exception:
  1. NameError: name 'Position' is not defined  
This is because Position must be defined before you can use it in an annotation unless you are using Python 3.10 or later.

Python 3.7+: from __future__ import annotations
Python 3.7 introduces PEP 563: postponed evaluation of annotations. A module that uses the future statement from __future__ import annotations will store annotations as strings automatically:
  1. from __future__ import annotations  
  2.   
  3. class Position:  
  4.     def __add__(self, other: Position) -> Position:  
  5.         ...  
This is scheduled to become the default in Python 3.10. Since Python still is a dynamically typed language so no type checking is done at runtime, typing annotations should have no performance impact, right? Wrong! Before python 3.7 the typing module used to be one of the slowest python modules in core so if you import typing you will see up to 7 times increase in performance when you upgrade to 3.7.

Python <3.7: use a string
According to PEP 484, you should use a string instead of the class itself:
  1. class Position:  
  2.     ...  
  3.     def __add__(self, other: 'Position') -> 'Position':  
  4.        ...  

1 則留言:

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