Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Setup VSCode for Python #18

Open
ngupta23 opened this issue May 3, 2020 · 0 comments
Open

Setup VSCode for Python #18

ngupta23 opened this issue May 3, 2020 · 0 comments
Labels

Comments

@ngupta23
Copy link
Owner

ngupta23 commented May 3, 2020

Setup

Creating a Workspace

  • Most likely scenario would be to create a workspace at a single repository level.
  • However, you can have cases where you have several repositories in a workspace (e.g. loading multiple repositories from a single BitBucket project). This can be achieved using a Multi-folder workspace where each folder in the workspace can be the root of a single repository. Refer to Understanding VSCode #96 for more details on this.

How to activate conda environment in VS code

Use this link.

  1. Make sure to change your default shell to "cmd". You can do that from the drop down in the "Terminal window". Once you do this, you can use all conda commands in this terminal.
  2. Setting your python interpreter
    • Do this as explained in the link above and do this for the whole workspace, not just for the open file.
  3. Change linter to pylint (Update: Use flake8 instead)
    • Press Ctrl + Shift + P >> Python: Select Linter >> Select 'pylint'
  4. Change type checker to 'mypy' - Can also use this for linting (Update: Use flake8 instead)
    • File >> Preferences >> Settings >> Search for "mypy" >>Add the target folders (must have folders with init.py under the target folder, else mypy will not check them recursively - more details here.
    • If this does not work, make sure the settings.json file under .vscode folder looks like this
  • Note: only add the rules below that you want to ignore (below if just an example)
{
    "python.linting.enabled": true,    
    "python.linting.pylintEnabled": true,
    "python.linting.flake8Enabled": true,
    "python.linting.mypyEnabled": false,
    "python.linting.flake8Args": [
        "--max-line-length=120",
        "--ignore=E402,F841,F401,E302,E305",   
    ]
    "python.pythonPath": "C:\\Users\\Nikhil\\.conda\\envs\\<conda_env_name>\\python.exe" 
}

Setup Extensions

Refer to #169

settings.json

PS: More details can be found in #170

AutoSave, Linting and Formatting

All linting options can be found here

In your config file (Control+shift+p, open settings (JSON)), add these options to enable autosave, autolinting, and auto formatting.

{
    "editor.rulers": [80, 88, 120],
    "editor.formatOnSave": true,
    "notebook.formatOnSave.enabled": true,
    "python.formatting.provider": "black",  
    "python.linting.enabled": true,
    "python.linting.lintOnSave": true,
    "python.linting.pylintEnabled": true,
    "python.linting.mypyEnabled": true,
    "files.autoSave": "afterDelay",
    "files.autoSaveDelay": 10000,
    "autoDocstring.docstringFormat": "numpy"    
}

Bracket Pair Colorization: extension is not maintained anymore since it is natively supported by VSCode. But you need to add this setting to enable it.

{
  "editor.bracketPairColorization.enabled": true,
  "editor.guides.bracketPairs":"active",
}

Module Search Paths for extensions

If some modules are not recognized by VSCode (for autocompletion), you can add them to the extraPaths list. After this is added, any modules used under this path will show autocompletion help when typing and will not complain about the reportMissingImports error. Note that this only impacts autocompletion. In the code, you still have to include the path in your sys.path for the module to be found, else the code will not run.

Link to this help

Pylance doesn't know which search paths will be used at the time you execute your Python code. You need to tell it. By default, Pylance will assume that the search paths will include the root of the workspace you open. It also automatically adds a subdirectory called "src" if it's present, since it's common practice to place your code within a subdirectory of that name. Any other subdirectories that should be included in the search path must be specified using the "python.analysis.extraPaths" setting.

{
    "python.analysis.extraPaths": ["myproject/folder1/source"]
}

NOTE: adding the path to the JSON settings is only for VSCode to recognize the module for autocompletion. For running the code, you will still need to add the path to python path. for example (depends on where you are running the code form)

import sys
import os

# https://stackoverflow.com/questions/16771894/python-nameerror-global-name-file-is-not-defined
if '__file__' in vars():
    print("We are running the script non interactively")
    path = os.path.join(os.path.dirname(__file__), os.pardir)
    print(f"Source Folder Path: {path}")
    sys.path.append(path)
else:
    print('We are running the script interactively')
    path = ".."
    print(f"Source Folder Path: {path}")
    sys.path.append(path)

Error: ValueError: attempted relative import beyond top-level package

Refer to this issue for more details

Important Notes about extensions and settings above

  • "python.formatting.provider": "black" could also be used
  • Syntax highlighting was not working for me (for function docstrings that contained type hints for return values) when I installed these extensions. I had to uninstall Python for VSCode per this link to make it work.
  • Note that sonarlint does type checking as well so mypy may be redundant. (need to verify this)
    • However, if you need to install mypy, it requires extra steps. These instructions can be found in the marketplace page for mypy
    • Run the following from the cmd terminal
python -m venv %USERPROFILE%\.mypyls

%USERPROFILE%\.mypyls\Scripts\pip install "https://github.com/matangover/mypyls/archive/master.zip#egg=mypyls[default-mypy]"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant