pythonpython-typingpylintpyright

Can I tell vscode that an argument is a custom class in python


I am working in vscode with Pylance and Pylint. Being able to use 'go to definition' and 'find all references' is extremely helpful for me. However, when I pass an instance of a custom class as an argument, it doesn't make the connection that this argument is that class and doesn't connect those dots. Is there a way to tell the linter that this argument is a certain class, so that when I find all references of say_goodnight inside of AlphaClass it also finds the instance inside of make_it_say_goodnight? In this simplified example, I could obviously move the function as a class method, but in my real code this wouldn't make sense.

class AlphaClass:
  def say_goodnight(self):
    print("Goodnight Kevin")

def make_it_say_goodnight(spam):
  print("Say Goodnight Kevin!")
  spam.say_goodnight()

macaulay = AlphaClass()
make_it_say_goodnight(macauly)

Solution

  • Just use type hints: https://peps.python.org/pep-0484/

    class AlphaClass:
      def say_goodnight(self):
        print("Goodnight Kevin")
    
    def make_it_say_goodnight(spam:AlphaClass):
      print("Say Goodnight Kevin!")
      spam.say_goodnight()
    
    macaulay = AlphaClass()
    make_it_say_goodnight(macauly)