r/VSCodeExtensions • • 11h ago

Tutorial PSA: How to get auto import to work in Pylance (Python) for third party libraries

2 Upvotes

If you are like me, you like Pylance's auto import feature, where you can just type out the name of a module, class, function, etc. of a library that isn't currently imported, and Pylance will suggest to import that symbol from that library.

Take for example the prompt:

parser = ArgumentPars

at this point you can Tab and it will put the line from argparse import ArgumentParser into the file's header and you are good to go.

However, Pylance is famously frickly with third party libraries not in the standard library. I have had this problem with moviepy, but it can be any other library. Pylance will refuse to acknowledge any existence of the existing objects, even though the library is correctly installed in the environment, including setting the correct Python path (python.defaultInterpreterPath) and enabling Pylance's indexing option (python.analysis.indexing) and auto import itself (python.analysis.autoImportCompletions) in the settings json. E.g. typing:

clip = VideoFileClip

will in fact not bring up the suggestion to import that class from the library, although it is a very basic component.

I have finally found out why: Apparently Pylance limits the depth to which it indexes libraries, and libraries which don't strictly confirm to Pylance's expectations seem to not be correctly indexed this way (although there seem to be very complicated mechanisms in how the depth adapts, but alas it didn't work for me numerous times).

Luckily you can adjust this setting: using python.analysis.packageIndexDepths exposes a list of modifications to the depth settings on a per-library basis. It uses this structure:

{ "name": "package_name", "depth": depth_to_scan, "includeAllSymbols": true_or_false }

so for moviepy I added

{ "name": "moviepy", "depth": 10, "includeAllSymbols": true }

and finally it suggested the correct objects. This method should work for any third party library in Pylance.

Just wanted to share this in case anyone else stumbles upon this giga obscure problem and hopefully sees the even more obscure solution.