简体   繁体   中英

Are there advantages of Python3 type hints over Python2?

As I understand it, Python2 had a type hint convention which resembled:

def geo_series(r, n) # type: (float, int) -> float
  return (1-r**n)/(1-r)

This has been replaced with Python3's system which looks like:

def geo_series(r: float, n: int) -> float:
  return (1-r**n)/(1-r)

My question is: what is the advantage of the Python3 system over that of Python2? It seems to me that they contain equivalent information. Since the type-checking is done by an external tool anyway, I see no major disadvantage to putting the type-hint in a comment.

Am I missing something? My best guess is that there are situations in which you can create some wacky type which makes the python3 type-checking more informative than the equivalent python2?

As Patrick mentioned in the comments, type annotations are part of the code, which means they can be accessed programmatically. For instance, in your python 3 example, you can use

>>> geo_series.__annotations__
{'r': float, 'n': int, 'return': float}

This programmatic access makes it possible to dynamically type check functions if you want to implement that.

An example of annotations being used within code is the dataclasses module . A field in a dataclass is detected based on whether it has a type annotation, which is only possible if the annotations are part of the code instead of in a comment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM