pycharm 可以建议或自动完成或插入类型提示吗? [英] Can pycharm suggest or autocomplete or insert type hints?

查看:53
本文介绍了pycharm 可以建议或自动完成或插入类型提示吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我想在我的 python2/3 代码中添加类型提示.在 Pycharm 中最简单的方法是什么?

Suppose I'd like to add type hints to my python2/3 code. What's the easiest way to do that in Pycharm?

除了 Pycharms 自己的类型推断,它如何帮助我编写类型提示?

Aside from Pycharms own type inference, how can it help me write type hint?

推荐答案

基本假设是您自己编写类型.

The underlying assumption is that you write your types yourself.

类型旨在对您打算的代码含义进行编码.虽然程序通常可以合理地推断人类意图,但归根结底,总是需要一些人为干预.

Types are meant to encode what you intend for your code to mean. While programs can often do a reasonable job at deducing human intent, at the end of the day, some human intervention is always going to be necessary.

(毕竟,如果程序推导出一组恰好与您的程序匹配的类型,但由于您的代码中的错误而最终完全错误怎么办?或者如果您打算让函数返回 Iterable[str] 但程序推导出List[str],反之亦然?)

(After all, what if a program deduces a set of types that happens to match your program, but ends up being completely wrong due to a bug in your code? Or what happens if you intended for your function to return an Iterable[str] but the program deduced List[str], or vice versa?)

也就是说,一些程序,例如 pytype 尝试自动为您推断类型.但是,我的理解是,这些类型的程序仍在大力开发中,还不能处理所有情况.

That said, there are some programs such as pytype that attempt to automatically infer types for you. However, my understanding is that these types of programs are still under heavy development and can't handle all cases yet.

如果您只想要存根,但不关心它们是否准确/包含有用的类型注释(也许您打算稍后编辑注释?),请使用stubgen",这是一个命令行实用程序,由安装 mypy 时的默认设置.

If you just want stubs, but don't care about having them be accurate/contain useful type annotations (perhaps you plan on editing the annotations later?), use "stubgen", which is a command line utility that's bundled by default when you install mypy.

但在一般情况下,我建议手动添加类型注释(可能从您最常用的文件开始),并在有意义的地方尝试使用辅助工具,如 stubgen 或 pytype.

But in the general case, I'd recommend adding type annotations by hand (perhaps starting with your most commonly-used files) and experiment with using auxiliary tools like stubgen or pytype where they make sense.

这篇关于pycharm 可以建议或自动完成或插入类型提示吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆