简体   繁体   English

Python:强制类型提示

[英]Python: enforce type hinting

I am wondering if there is a way to enforce type hints inside the Python projects?我想知道是否有办法在 Python 项目中强制执行类型提示

Currently, I am using mypy pre-commit hook inside .pre-commit-config.yaml :目前,我在.pre-commit-config.yaml中使用mypy 预提交钩子

- repo: https://github.com/pre-commit/mirrors-mypy
  rev: v0.931
  hooks:
    - id: mypy

Using this hook, I will (correctly) not be able to commit the following piece of code due to type error when calling add function:使用这个钩子,在调用add function 时,由于类型错误,我将(正确地)无法提交以下代码:

def add(a: int, b: int) -> int:
    return a + b

add(a=1.0, b=2.0)

However, using above combination of mypy and pre-commit hooks , type hints are still not fully enforced and I will be able to commit the following piece of code where no type hints are used:但是,使用上面的mypypre-commit hooks组合,类型提示仍然没有完全强制执行,我将能够提交以下不使用类型提示的代码:

def add(a, b):
    return a + b

I would also be curios, if enforcing type hints in a dynamically typed language such as Python is even a good idea in the first place?我也会好奇,如果在诸如 Python 之类的动态类型语言中强制执行类型提示甚至是一个好主意吗? I know that I could opt instead for some statically typed language (eg Java) for my project, however, the reason I want to use Python with enforced type hints is because this allows me to rely on existing Python libraries (eg Tensorflow) while ensuring that the code written is of better quality because of specified types in function signatures.我知道我可以为我的项目选择一些静态类型语言(例如 Java),但是,我想使用带有强制类型提示的 Python 的原因是因为这允许我依赖现有的 Python 库(例如 Tensorflow)同时确保由于 function 签名中的指定类型,编写的代码质量更好。

Mypy exposes a bunch of option that you can set to enforce stricter or looser type checking, see for example enter link description here . Mypy 公开了一系列选项,您可以设置这些选项以强制执行更严格或更宽松的类型检查,例如,请参见在此处输入链接描述 For your case it would probably be disallow_untyped_defs, disallow_incomplete_defs, disallow_untyped_calls对于您的情况,它可能是disallow_untyped_defs, disallow_incomplete_defs, disallow_untyped_calls

You have several options to set them, for example using a mypy.ini file, or if you want to keep everything in your pre-commit.yaml, you can add several command line arguments.您有几个选项来设置它们,例如使用 mypy.ini 文件,或者如果您想将所有内容保留在 pre-commit.yaml 中,您可以添加几个命令行 arguments。 For your exact case, that would look like对于您的确切情况,这看起来像

- repo: https://github.com/pre-commit/mirrors-mypy
  rev: v0.931
  hooks:
    - id: mypy
      args: [--disallow_untyped_defs, --disallow_incomplete_defs, --disallow_untyped_calls]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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