【问题标题】:How can flycheck give warning if the object's function does not exist?如果对象的功能不存在,flycheck 如何发出警告?
【发布时间】:2021-03-21 17:10:55
【问题描述】:

我正在使用lsp for Python。我想知道一个对象的功能,如果没有定义,lsp 可以使用flycheckjedi 给出错误/警告或下划线吗?我知道这很有挑战性,我只是想知道这是否可能。

示例python代码:

class World():
    def hello():
        print("hello")


obj = World()
obj.hello()()
obj.foo()   # <=== hoping to see: No definitions found for: foo and underline foo()
~~~~~~~~~

由于foo()不是World下的对象;我希望lsp 给我一条警告消息,让我知道该函数在对象定义下不存在。


可在此处查看示例配置:https://github.com/rksm/emacs-rust-config

注释掉9..3548 行并添加以下(use-package python :ensure nil) 保存和安装包。然后打开一个python文件,M-x lsp启动lsp,

【问题讨论】:

  • Python 真的不容易静态分析。如果 linter 可以在最简单的情况下执行此操作,我会感到非常惊讶。
  • 老实说,我不确定 linter 能否做到这一点,我对此感到好奇。当我尝试将光标放在不存在的模块上并尝试跳入它时,flycheck 返回该模块不存在,但动态我什么也没说
  • @amalloy 但也许是绝地 (github.com/davidhalter/jedi)

标签: python emacs jedi flycheck


【解决方案1】:

这是一个以编程方式检查给定对象是否具有任意名称的方法的函数:

def method_exists(obj_instance, method_name_as_string):
    try:
        eval("obj_instance." + method_name_as_string + "()")
    except AttributeError:
        print("object does not have the method " + method_name_as_string + "!")
        return False
    else:
        print("object does not has the method " + method_name_as_string + "!")
        return True

method_exists(obj, "foo") #returns False
method_exists(obj, "hello") #returns True

它返回一个布尔值,而不是出错并中断程序的执行。从那里,您可以发出飞行检查警告或根据信息执行几乎任何您想做的事情。它只检查实例方法,但可以很容易地适应检查与对象无关的类方法或函数。

【讨论】:

  • 我想在键入我的代码而不编译或运行它的过程中实现这个结果,就像 flycheck 所做的那样,并突出显示对象下未定义的模块。我不确定如何将您的解决方案与 flycheck 结合起来并突出显示那些缺失的模块
猜你喜欢
  • 2022-11-27
  • 2021-06-17
  • 2018-09-26
  • 1970-01-01
  • 2013-01-11
  • 2011-01-03
  • 1970-01-01
  • 2016-12-13
相关资源
最近更新 更多