microsoft / pylance-release

Documentation and issues for Pylance
Creative Commons Attribution 4.0 International
1.7k stars 768 forks source link

How to "inject" context into namespace so that pylance is aware of those variables #3075

Closed ya5has closed 2 years ago

ya5has commented 2 years ago

I know this is a very odd scenario. Consider the code below:

import spot_name_functions as SNF
import Enumerations_Various as EV
import delay
import logger

SNF.set_Current_FMS_VSpeed_STATUS(EV.STATUS_NORM)
vista.wait(delay.max_delay())
actual = IAS_Approach_Climb_Speed_Is_Auto.getValue()
expected = True
logger.test(actual, '==', expected)

Notice that vista and _IAS_Approach_Climb_Speed_IsAuto are clearly not imported (or defined) in this file; therefore pylance shows a squiggly line warning. However these two are special-objects that just works when the file is run in a proprietary software at my work. I like to use vscode to explore these files, debug them by attaching it to said proprietary software process and modify them if needed. I know the locations of the files in which these special-objects are defined.

Now my question is how can I inform pylance about these special objects so that I don't get the warning? (and hopefully get code-completion). I have the following constraints though:

I have been ignoring these warnings but on any given file there might be over 100 occurrences of these and it stops me from knowing truly undefined variable when I edit extensively. I'm thinking of writing a custom vscode extension that runs a script when I open any python file and maybe interact with the language server and/or define these objects. I don't know if that sounds stupid. Is that even possible? If so, can you point me in the right direction on how I can achieve that? Is there a easier solution?

erictraut commented 2 years ago

Pylance is built on top of Microsoft's open-source type checker called Pyright. Pyright has a facility for extending the "builtins" namespace. For details, refer to this documentation. The basic idea is to create a type stub called __builtins__.pyi in your project's root directory. Within this type stub file, you can define symbols (functions, variables, classes, etc.) that should be "injected" to all modules within your project.