1

In Python, I am dynamically creating a namespace by modifying globals().

For some background, I'm masking/filtering another file to get rid of some unwanted members and wrap foreign functions with a mutex. The masked file contains auto-generated bindings for a relatively large C library that is not thread-compatible.

However, this confuses VS code syntax highlighting and auto-completion: the wrapper file's members, which are added dynamically on import time, are not recognized, and the namespace is seen as empty.

As a workaround, I thought about filtering the original namespace in place rather than masking it, but would prefer to preserve it as-is so we can still access the unmodified namespace if desired. Also, this way the IDE's namespace info would still be incorrect: dynamic changes would not be taken into account and excluded members would still be shown.

As a last resort, supposedly I could write some code to generate a PEP 484 stub file (.pyi), but don't like the idea of another dynamic file that is effectively unnecessary if only the IDE were smarter.

Is there an option to make VS code agnostic of globals(), or any other workaround to make it recognize the dynamic members?

mara004
  • 1,435
  • 11
  • 24
  • Another idea would be to make a `.pyi` file that is a symlink to the original. – mara004 Aug 01 '23 at 01:00
  • Unfortunately, this is impossible at present. Because VS Code's language server relies on static analysis of your code to provide syntax highlighting and auto-completion, and it cannot analyze code that is generated dynamically at runtime. – MingJie-MSFT Aug 01 '23 at 02:59
  • @MingJie-MSFT I see, but nevertheless I would need some practical workaround for now to get highlighting back. Apart from that, I'm thinking about filing a feature request with VS Code / Pylance. Maybe they can add some directive to selectively compile a file and get its namespace using `dir()` inspection rather than static analysis? Something like `# ide: compile namespace` similar to directives of code style checkers and coverage tools. – mara004 Aug 01 '23 at 11:04
  • @MingJie-MSFT Or is there another language server I can use? I heard somewhere the previous one did some dynamic analysis? – mara004 Aug 01 '23 at 11:08
  • Perhaps you could try PyCharm? VSCode is currently only a lightweight editor. – MingJie-MSFT Aug 03 '23 at 01:17
  • Thanks for the suggestion, I may give it a try. – mara004 Aug 03 '23 at 21:44

0 Answers0