如何在 PyCharm 中添加类型提示?
How to add type hints in PyCharm?
我经常发现自己必须在 PyCharm 中启动调试会话只是为了检查变量并使用 something.__class__
查找其 class 以便我可以插入类型提示代码以使其更具可读性。
有没有办法在 PyCharm 中通过上下文操作、在 VSCode 或其他工具中自动执行此操作?
对于VSCode,有一些扩展用于添加类型提示:
- Python Type Hint
- Pylance in combination with IntelliSense for Python
我使用了 IntelliSense。
Is there a way to do it automatically in PyCharm via a context action
嗯不!因为如果您在 run-time 处获得 subclass 的类型提示,这并不意味着您不想(或不应该)插入 superclass 的类型提示. (或者完全不同的 class 的类型提示,如果它是 Union, or even one of the unsupported features like an Intersection, etc... The possible combinations are countless and even tools like mypy 则无法静态检查它们,更不用说动态检查了...)
因此无法有意义地自动插入类型提示,因为 IDE 无法推断所有可能的 运行 时间类型,这是程序员的工作。
via a context action
上下文操作仅限于来自 JetBrains 插件市场的 Adding type hints but these still require you to fill in the fields by hand. You could try and use Inlay Hints but Python isn't part of the default inlay languages included in PyCharm (check the list at Settings
>
Editor
>
Inlay Hints
.) You could try a specific plugin to work for the Python inlay hints, for example Python Inlay Hints,但我认为它不会完全符合您的要求。
最后,有一个名为 Collect run-time types information for code insight
的选项,请参阅 issue PY-38900 但根据我个人的经验,这会导致莫名其妙的错误,并且通常会导致陈旧的缓存导致比它解决的问题更多的问题(阅读 SO a 上的帖子很少有 Django 用户觉得它有用,但我也不认为它能满足您的需求。
您在 PyCharm 中尝试过 Adding type hints 吗?
VSCode-Python不支持这个功能,我在GitHub提交了一个feature request。
我经常发现自己必须在 PyCharm 中启动调试会话只是为了检查变量并使用 something.__class__
查找其 class 以便我可以插入类型提示代码以使其更具可读性。
有没有办法在 PyCharm 中通过上下文操作、在 VSCode 或其他工具中自动执行此操作?
对于VSCode,有一些扩展用于添加类型提示:
- Python Type Hint
- Pylance in combination with IntelliSense for Python
我使用了 IntelliSense。
Is there a way to do it automatically in PyCharm via a context action
嗯不!因为如果您在 run-time 处获得 subclass 的类型提示,这并不意味着您不想(或不应该)插入 superclass 的类型提示. (或者完全不同的 class 的类型提示,如果它是 Union, or even one of the unsupported features like an Intersection, etc... The possible combinations are countless and even tools like mypy 则无法静态检查它们,更不用说动态检查了...)
因此无法有意义地自动插入类型提示,因为 IDE 无法推断所有可能的 运行 时间类型,这是程序员的工作。
via a context action
上下文操作仅限于来自 JetBrains 插件市场的 Adding type hints but these still require you to fill in the fields by hand. You could try and use Inlay Hints but Python isn't part of the default inlay languages included in PyCharm (check the list at Settings
>
Editor
>
Inlay Hints
.) You could try a specific plugin to work for the Python inlay hints, for example Python Inlay Hints,但我认为它不会完全符合您的要求。
最后,有一个名为 Collect run-time types information for code insight
的选项,请参阅 issue PY-38900 但根据我个人的经验,这会导致莫名其妙的错误,并且通常会导致陈旧的缓存导致比它解决的问题更多的问题(阅读 SO a 上的帖子很少有 Django 用户觉得它有用,但我也不认为它能满足您的需求。
您在 PyCharm 中尝试过 Adding type hints 吗?
VSCode-Python不支持这个功能,我在GitHub提交了一个feature request。