Tuesday, 1 August 2023

PyCharm add python extra path: Custom module path for missing import resolution

I'm coming from VSCode into PyCharm as my team wants me to use PyCharm. It's a hard requirements.

In my current python project, I have a python code where we didn't commit all the generated (grpc) python code. To generate this, let's say we run a command like: bazel build //...

The project will run only if you use bazel, but bear with me. It's supposedly not a complex question.

The directory looks like this:

    - workspaceFolder (source root)
    |-- models
      |-- dao_user.py
      |-- dao_accounts.py
    |-- database
      |-- transaction.py
      |-- google_spanner.py
    |-- service
      |-- grpc_user_svc.py
    ...
    |-- .bazel-bin (auto-generated by bazel build)
      |-- api
        |-- protos
          |-- awesome_pb2.py
          |-- awesome_service_pb2.py
          |-- authentication.py

However, this will output the generated code into a different folder inside ${workspaceFolder}/.bazel-bin/. Of course, this should give an issue in the PyCharm interpreter code where we would be missing some imports because the python code is not in the workspace folder (a.k.a the project source root).

# Pycharm has issues finding this modules
from api.protos.authentication import AuthenticationRequest 
from api.protos import awesome_pb2 as api_awersome_pb2
from api.protos import awesome_service_pb2

My question is, how can tell PyCharm to get the above imports to be analysed from .bazel-bin folders?

  • I don't want to move the code from .bazel-bin.
  • I want PyCharm interpreter to understand the extra source code path from .bazel-bin/

I'm pretty sure it's possible. I have made it work in VSCode. I can do this in VSCode by having the following configuration settings:

// .vscode/settings.json
{ 
 "python.analysis.extraPaths": [
    "${workspaceFolder}/bazel-bin/api",
    "${workspaceFolder}/bazel-bin/cloud",
    "${workspaceFolder}/bazel-bin/storage"
  ],
  "python.linting.pylintPath": "pylint",
  "python.linting.pydocstyleEnabled": false,
  "python.linting.banditEnabled": false,
  "python.linting.flake8Enabled": false,
  "python.linting.prospectorEnabled": false,
  "python.languageServer": "Pylance",
  "python.analysis.autoImportCompletions": false,
}

Any help will be appreciated. My team also doesn't know how to do this in PyCharm.



from PyCharm add python extra path: Custom module path for missing import resolution

No comments:

Post a Comment