Pyright: goto definition in dictionaries not working: No location found

Hello,

in a python project, I cannot always go to definitions when dictionaries are involved. I made a minimal fictive working example:

class Hobby:
    def __init__(self, hobby):
        self.hobby = hobby

    def print_hobby(self):
        print(self.hobby)


friends = ["Alice", "Bob"]

HobbyFriends = {}
for friend in friends:
    HobbyFriends[friend] = Hobby("Encryption")

HobbyMallory = Hobby("Interception")

HobbyMallory.print_hobby() # gd is WORKING on print_hobby
for friend in friends:
    HF[friend].print_hobby() # gd is NOT working on print hobby

If I press gd while the cursor is on print_hobby() in the line marked WORKING I get to
the definition in the class, but when the cursor is on print_hobby() in the line marked NOT
I am not forwarded to the definition within the class, which is annoying in the real project …

In ‘lsp.log’ I get:

[INFO][2023-03-03 08:51:09] ...lsp/handlers.lua:364	"textDocument/definition"	"No location found"

neovim: 0.9.0-nightly
pyright: 1.1.296

Maybe somebody could help me figuring out what I am doing wrong…

Thanks in advance!

gd isn’t working because it can’t find print_hobby(). It can’t find it for 2 reasons:

  • HF is undefined and should be HobbyFriends.
  • HobbyFriends = {} is currently seen as a dict[unknown, unknown] and must be type hinted.

This version works for me:

from typing import Dict

class Hobby:
    def __init__(self, hobby):
        self.hobby = hobby

    def print_hobby(self):
        print(self.hobby)


friends = ["Alice", "Bob"]

HobbyFriends: Dict[str, Hobby] = {}
for friend in friends:
    HobbyFriends[friend] = Hobby("Encryption")

HobbyMallory = Hobby("Interception")

HobbyMallory.print_hobby()
for friend in friends:
    HobbyFriends[friend].print_hobby()