Search code examples
ptvs

How to configure PythonAnalyzer to look for standard library typings?


I am creating a PythonAnalyzer using the following code:

var interpreterFactory = InterpreterFactoryCreator.CreateAnalysisInterpreterFactory(
                                        PythonLanguageVersion.V36.ToVersion());
var analyzer = PythonAnalyzer.Create(interpreterFactory);

Later on I also create and analyze a simple python module, that looks like this:

name = input('What is your name?\n')
print('Hi, %s.' % name)

Then I do module.Analysis.GetValuesByIndex("name", 4).

At this moment I expected the "value" to be 'str', because that's what Visual Studio shows when I open the same file in it. However, I get 'object' instead. So it seems that the PythonAnalyzer when constructed as mentioned above lacks some important information about where to look for standard library and/or its types.

Unfortunately, the documentation on PythonAnalyzer is lacking, so I was hoping the community could help understand how to configure it properly.


Solution

  • Congratulations on getting so far :)

    What you're hitting here is the fact that CreateAnalysisInterpreterFactory is really intended for "pure" cases, where you have access to all the code that you're trying to analyze and nothing needs to be looked up. It is mostly used for the unit tests, or as a fallback when no copies of Python are installed. Depending on precisely which version of PTVS you are using, the bare information you're getting is either coming from DefaultDB\v3\python.pyi or CompletionDB\__builtin__.idb, both of which are somewhat lacking (by design).

    Assuming you have a copy of Python installed, I would suggest creating an instance of InterpreterConfiguration with all of its details, and passing that to CreateInterpreterFactory (without "Analysis").

    If you're on the latest sources (strongly recommended), this may run the interpreter in the background to collect information from it (you can control caching of this info with the DatabasePath and UseExistingCache members of InterpreterFactoryCreationOptions). If you are using the older version still, you'll need to trigger a completion DB regeneration or have one that you've created through VS.


    And a final caveat: this part of PTVS is currently under some pretty heavy development at time of writing, so you'll either want to keep updating the version you're working against or stick with a slightly older one. Also feel free to post questions like this on the GitHub site, as while this is technically public API, it's barely documented at all and so the best help will come from the dev team.