PyCharm:如何推断在运行时创建的对象类型 [英] PyCharm: how to infer types of objects created at runtime

查看:27
本文介绍了PyCharm:如何推断在运行时创建的对象类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用一个创建对象的库,并在运行时将它们添加到全局命名空间.

I am trying to use a library that creates objects, and adds them to the global namespace at runtime.

PyCharm 找不到对象的引用,因为它们最初不在命名空间中.

PyCharm cannot find the references to the objects, because they aren't originally in the namespace.

如何让 PyC​​harm 自省不抱怨找不到参考..."?我不想使用 noinspection 标签.

How can I get PyCharm introspection to not complain "Cannot find reference..."? I don't want to use noinspection tags.

示例代码

为了帮助澄清我的问题,我已经制定了使用 PyCharm 中运行时创建的对象的示例代码.

To help make my question clear, I have drawn up sample code of using an object created at runtime in PyCharm.

main.py

from some_import import some_obj_1


if __name__ == "__main__":
    print(f"obj_1.some_attr = {some_obj_1.some_attr}")

some_import.py

class SomeClass:
    def __init__(self, attr_init: int = 0):
        self.some_attr = attr_init


globals()["some_obj_1"] = SomeClass(1)

运行main.py的输出:

obj_1.some_attr = 1

我在 PyCharm 中看到的:

What I see in PyCharm:

相关文章

动态运行时PyCharm 2.7 中的类型推断

本文建议启用收集运行时类型信息以了解代码.但是,启用此设置并运行调试器并没有解决我的问题.

This article suggests enabling Collect run-time types information for code insight. However, enabling this settings and running the debugger did not solve my problem.

可能的解决方案

  • 制作 PyCharm 存根文件
  • 使用 PyCharm noinspection 标签 + 类型提示抑制错误消息
    • 这是手动",因此我不太喜欢这个解决方案
    • Making a PyCharm stub file
    • Suppressing the error message using PyCharm noinspection tag + a type hint
      • This is "manual", and thus I don't like this solution very much
      # noinspection PyUnresolvedReferences
      from some_import import some_obj_1, SomeClass
      
      some_obj_1: SomeClass
      
      
      if __name__ == "__main__":
          print(f"obj_1.some_attr = {some_obj_1.some_attr}")
      

      <小时>

      这是使用 Python 3.7.6PyCharm 2019.2.5 CE 制作的.

      推荐答案

      下面的链接让我觉得只要使用模块名称就可以了.

      The below link makes me think it is possible just by using the module name.

      使用 Python 控制台运行"中全局变量的行为

      我已经编写了这段代码,但是我很难测试,因为我使用的是 Spyder 并且它适用于您最初的尝试

      I've written this code but it's tough for me to test as I'm using Spyder and that works with your original attempt

      import some_import as si
      
      
      if __name__ == "__main__":
          print(f"obj_1.some_attr = {si.some_obj_1.some_attr}")
      

      这篇关于PyCharm:如何推断在运行时创建的对象类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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