0

I am using lsp for Python. I was wondering for an object's function, if there is no definition for it, can lsp give an error/warning or underline using flycheck or jedi? I know this is challenging I just wonder that's possible or not.

example python code:

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


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

Since foo() is not an object under World; I want lsp to give me a warning message letting me know that that function does not exist under the object definition.


Example configuration could be seen here: https://github.com/rksm/emacs-rust-config

Comment out the lines 9..35 and 48 and add the following (use-package python :ensure nil) save and install packages. Then open a python file, and M-x lsp to start lsp,

alper
  • 2,919
  • 9
  • 53
  • 102
  • Python really is not easy to statically analyze. I would be pretty surprised if a linter could do this for anything but the simplest cases. – amalloy Mar 21 '21 at 19:08
  • Honestly I am not sure that can linter could do it or not that's I was curious about it. When I attemt to bring cursor on top of the non-exist module and try to jump into it , flycheck returns that the module does not exist , but dynamically I does not say anything – alper Mar 21 '21 at 19:22
  • @amalloy But maybe with jedi (https://github.com/davidhalter/jedi) – alper Mar 22 '21 at 14:20

1 Answers1

0

This is a function to programatically check if a given object has a method with an arbitrary name:

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

It returns a boolean instead of erroring out and interrupting the program's execution. From there, you can give a flycheck warning or do pretty much whatever you want if the information. It is only checking for instance methods but can be easily adapted to also check for class methods or functions not associated with objects.

  • I want to achieve this result during typing my code without compile or running it, like flycheck does and highlight the modules that are not defined under the object. I am not sure how can I combine your solution along with flycheck and highlight those missing modules – alper Apr 17 '21 at 12:19