Visual Studio Code – Virtual Environment for Python Code Styling Validation

“Code is read much more often than it is written.” We may spend a few minutes writing a piece of code to View/Edit the data in a Page Section. Once it’s completed, we never going to write it again. But we definitely have to read it again. This piece of code might remain part of our project for a very long time. Every time we go back to that script, we’ll have to remember what that code does and why we developed it, so readability matters.

It can be difficult to remember what a piece of code does a few days, or weeks after we wrote it. But If we follow a ‘Styling Guide’, we can be sure that we named our variables well. We’ll know that we’ve added enough white space so it’s easier to follow logical steps in our code. We’ll also have commented on our code well. All this will mean our code is more readable and easier to come back to. Following the rules in a “Styling Guide” make learning Python a much more pleasant task. Writing a clear, readable code shows professionalism.

PEP 8 — the Style Guide for Python Code

“Readability counts.” — The Zen of Python

Why Readability count? Other people, who may have never met us or seen our coding style before, will have to read and understand our code. If we follow a global standard guideline, it will make it easier for others to quickly learn the business logic in our code. This is why we need PEP 8. PEP 8 sometimes spelled PEP8 or PEP-8 or “Python Enhancement Proposal”, is a document that provides coding conventions, guidelines, and best practices on how to write Python code. The primary focus of PEP 8 is to improve the readability and consistency of Python code. PEP 8 has emerged as the style guide that most of the python projects adhere to and it’s learned and followed by the majority of python developers across the globe. So it even helps us to quickly onboard the new hires into our project and to make them feel comfortable with our code base.

Ensure our Code Follows PEP 8:

Linters are programs that analyze code and flag errors. They provide suggestions on how to fix the error. Auto formatters are programs that refactor our code to conform with PEP 8 automatically. Linters just help us to identify the issues, But formatters will auto-resolve most of our styling issues.

  • PyCodeStyle linter to check our Python code against the style conventions in PEP 8.
  • PyDocStyle which is used to check the documentation/docstrings in our code.
  • Black which auto-formats code following most of the rules in PEP 8 we documented above.

Linters, Formatters and Static Analysis tools are more effective and useful when installed as extensions to our IDE, as they flag errors and stylistic problems while we write code.

Lets see how to setup a python virtual environment to automate styling validation in VS Code.

Download and install Python 3.8.3. When installing, select all the ‘Optional Features’ also

Download and install Visual Studio Code

Add the Python Path in System Environment Variables and User Environment Variables.

Check the installation by typing python –version

Install the following extensions [optional] for the Visual Studio Code.

  • Python
  • Github
  • Git History

Open the Project folder in VS Code.

Run the following command in the VS Code terminal to create a virtual development environment.

python -m venv venv-django
cd .\venv-django\Scripts\ 
.\Activate.ps1
cd..
cd..
python -m ensurepip
python -m pip install --upgrade pip
pip install -r .\requirements.txt

When we install the requirements.txt, all the styling linter, formatted, and code analysis tools will also be installed.

appdirs==1.4.4
attrs==19.3.0
black==19.10b0
click==7.1.2
pathspec==0.8.0
pep8==1.7.1
pip==20.3.3
pycodestyle==2.6.0
pydocstyle==5.0.2
regex==2020.6.8
setuptools==41.2.0
snowballstemmer==2.0.0
toml==0.10.1
typed-ast==1.4.1
wheel==0.34.2

Use this settings.json under .vscode folder which will serve as a VS Code settings file specific to our python project.

{
    "workbench.settings.editor": "json",
    "breadcrumbs.enabled": true,
    "editor.minimap.enabled": true,
    "editor.renderWhitespace": "none",
    "editor.tabSize": 4,
    "editor.insertSpaces": true,
    "editor.formatOnSave": true,
    "editor.trimAutoWhitespace": true,
    "editor.renderControlCharacters": false,
    "github.statusbar.color": false,
    "git.autofetch": true,
    "git.rebaseWhenSync": true,
    "git.confirmSync": false,
    "git.enableSmartCommit": true,
    "python.pythonPath": "venv-django\\Scripts\\python.exe",
    "python.formatting.provider": "black",
    "python.formatting.blackArgs": [
        "--line-length=125"
    ],
    "python.linting.enabled": true,
    "python.linting.pycodestyleEnabled": true,
    "python.linting.lintOnSave": true,
    "python.linting.pylintEnabled": false,
    "python.linting.maxNumberOfProblems": 10000,
    "python.linting.pydocstyleEnabled": true,
    "python.linting.pycodestyleArgs": [
        "--max-line-length=125"
    ]
}

So now you’ll be able to see all the styling related issues in the ‘Problems’ tab which are mentioned in PEP-8.

Press Ctrl + S or Save, most of the issues identified by the Linter will be resolved by ‘Black’.

Along with auto-formatting when Save, I also frequently use, ‘Format Document’, ‘Convert Indentation to Tabs’, ‘Indent using Tabs’, ‘Trim Trailing Whitespace’ option in VS Code Command Palette to maintain consistent styling across all my source files.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s