microsoft / pylance-release

Documentation and issues for Pylance
Creative Commons Attribution 4.0 International
1.67k stars 770 forks source link

Please add the support for function jumping feature when using importlib #6031

Closed sishau closed 1 week ago

sishau commented 1 week ago

when importing libraries using regular import statement, I am able to jump to the function definition by pressing ctrl+left click. However, this functionality is missing when using importlib for importing libraries. It would be greatly beneficial if this feature could be added to improve the overall usability of the project. image image

debonte commented 1 week ago

Your importlib approach is too dynamic for a static type checker to handle. You could use if TYPE_CHECKING to tell Pylance which imports you want it to consider at type checking time.

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    if my_args.project == 'projectA':
        from lib.projectA import libx
    elif my_args.project == 'projectB':
        from lib.projectB import libx
    else:
        raise ValueError("Invalid project name")
else:
    libx = importlib.import_module('lib.' + my_args.project + '.libx')

libx.libx().run()
sishau commented 1 week ago

@debonte No, it's not a problem for me that there are two options when jumping, I can choose them manually. My question is, if I use importlib.import_module('lib.' + my_args.project + '.libx'); would it be possible to give the same options as from... import... at the jump, instead of saying "No definition of run was found"?

heejaechang commented 1 week ago

we are static analyzer, we can't figure out what my_args.project will return, so what 'lib.' + my_args.project + '.libx' expression would result to.

it requires actually running code. notebook (jupyter extension) with cell actually ran might be able to provide that information but not pylance