Introduction¶
Although Iāve been tinkering with python for my Data Science projects since 2016, I only started coding professionally at the end of 2018. It wasnāt easy to get accustomed to the workflow by any means and the rigor of a production and test driven environment was something completely different from what I was used to š. I had only been using all the tools and packages integrated into the amazing Anaconda Distribution which means Spyder as the IDE and the trusted old Jupyter Notebook for experimentation. I still use jupyter notebook, however, Iāve picked up VS Code as my primary editor not only due to the fact that everyone at my workplace uses that but also in my opinion itās one of the best language agnostic code editor, period š. So this post is an assortment of all the tools and practices that Iāve picked up throughout my development journeyš„.
Here Iām using Linux as my primary development OS and many of the instructions apply directly to MacOS also. However, if you are doing python in VS Code on MacOS or Windows, I encourage you contribute and extend this guideline. Now letās jump in š¦.
Table of Contents ššĀ¶
Setting up VS Code on Your Machine š¶Ā¶
Installing VS Code¶
Installing VS code is easy across all operating systems.
Just go to the link here and select the distribution that corresponds to your OS.
Download the file and install
Running VS Code¶
After youāve completed the installation, open terminal and
cd
to your project folder. Then type:
$ code .
This will open your project in VS Code. Familiarize yourself with the GUI if youāre using this for the first time. The left most stripe gives you multiple options and hovering over the icons will show you their corresponding functionalites. If youāre using any third party extensions, their icons may also appear. Clicking on each of them will bring up extra actions in the succeeding column.
The default icons are (from top to bottom):
Explorer
Search
Source Control (Git)
Debug
Extensions
Using the Integrated Terminal¶
If you arenāt migrating from any other terminal and havenāt set up your preferred keybindings
then you can open the integrated terminal by pressing ctrl + ~
on your keyboard. This terminal is an exact replica of your bash
/zsh
terminal and can perform almost anything that youād normally do in those. From now an on, unless explicitly mentioned otherwise, weāll be using the integrated terminal for the versatility and convenience it provides.
Setting up Environments š²Ā¶
Why Environments are Necessary¶
The main purpose of using environments is to create a segregation between the dependencies of different python projects. It eliminates (at least tries to) dependency conflicts since each project has itās own set of dependencies, isolated from one another.
Suppose you are working on two projects, Project_1
and Project_2
, both of which have a dependency on the same library, letās say the awesome Requests
library. Dependency conflict will arise, if for some reason, the two projects need different versions of Request
library. For example, maybe Project_1
needs v1.0.0
, while Project_2
requires the newer v2.0.0
.
This can easily be avoided by using individual environment for each project where all the dependencies of the corresponding project will reside. There are multiple ways you can create environment. Weāll mainly focus on creating python3 based conda environment
and native virtual environment
.
Conda Environment¶
Installing Anaconda Distribution¶
Install anaconda on your machine. I personally prefer miniconda over the full fledged anaconda. The installation guide can be found here:
Creating Conda Environment¶
After installing anaconda, to create a python3 environment with a specific version of python, type the following command. This will create an environemnt named myenv
with python 3.7:
$ conda create -n myenv python=3.7
Activating Conda Environment¶
After creating the conda environment, type the folling command to activate the myenv
environment:
$ conda activate myenv
Virtual Environment¶
Installing python3-venv¶
To create virtual environment, first you need to install python3-venv
. Run:
$ sudo apt update
$ sudo apt-get install python3-venv
Creating Virtual Environments¶
Create a virtual environment named myenv
via running:
$ python3 -m venv myenv
You should see a folder named myenv
in your current directory. This is the folder where all your project-specific dependencies are going to reside.
Selecting & Switching Between the Environments in VS Code¶
Press
ctrl+shift+P
to open VS Codeāscommand palette
. You should be seeing something like this:Type
interpreter
in the search box. And select thePython: Select Interpreter
option. You should see a list of all the available (both conda and virtual environments are shown) python environments. You should also see your recently createdmyenv
environment there. Toggle and select your environment and you are good to go.
Installing Third Party Packages¶
To install third party packages/libraries/moduels from pip
or conda
,
Activate your respective environments
Depending on the package manager you want to use, type either:
$ pip install <package_name>
or
conda install <package_name>
Running Python Scripts with Code Runner šĀ¶
Installing Code Runner Extension¶
Click the extension icon on the left most stripe and type code runner
in the search bar. You should see the extension popping up in the first row. Click and install.
Setting up Code Runner¶
By default, code runner uses its own panel for showing the results after you run your python script. However, itās better to set it up in a way that it will show the results in the integrated terminal.
Press
ctrl+,
to open up the settings panelOn the search bar type
code runner terminal
You should be able to see an option named
Code-runner: Run In Terminal
Check off the option and you are good to go š°
Running Python Scripts¶
Create and select your python environment (See the instructions here.)
Create a new file via
ctrl+N
Press
ctrl+s
to save the file and give it a name with.py
extensionWrite down your python code in the file
Press
ctrl+alt+N
to run the code via Code RunnerYou should see your results in the integrated terminal š¬
To run only a selected lines of codes, select the lines you want to run and press
ctrl+alt+N
.
Linting & Formatting šĀ¶
Linters perform static analysis of source codes and check for symantic discrepancies. When you lint your code, itās passed through a basic quality checking tool that provides instructions on how eliminate basic syntactic inconsistencies.
Formatters are similar tools that tries to restructure your code spacing, line length, argument positioning etc to ensure that your code looks consistent across different files or projects.
Python offers you a plethora of linters and formatters to choose from. Flake8, pyflakes, pycodestyle, pylint are some of the more widely used linters and black, yapf are two newer members in the code formatting space.
However, not to bombard you with a deluge of information, we are taking an opinionated route that gets the job done without a hitch. Letās talk about Flake8
and Black
.
Flake8¶
Flake8 is a Python linting library that basically wraps three other linters, PyFlakes, pycodestyle and Ned Batchelderās McCabe Script. Itās one of the better linters out there that has very low false positive rate. It checks your code base against PEP8 programming style, programming errors (like ālibrary imported but unusedā and āUndefined nameā) and cyclomatic complexity.
For more details on the nitty gritties of flake8, check out their github project here.
Black¶
Black is known as the uncompromised Python code formatter. Unlike flake8 or pycodestyle, it doesnāt nag you when there are style inconsistencies. It just fixes them for you. Black does not have a lot of options to tinker with and has a lot of opinion on how your code should look and feel. You might not always agree with the decisions that black takes for you but if you can get along with the style that black imposes on you, it can take care of the unnecessary hassles of formatting your codes to keep it conistent across multiple projects or organization.
Before formatting with black
After formatting with black
Setting Up Linters in VS Code¶
Luckily VS Code comes with both flake8
and black
formatter lurking in the settings. To set them up:
Press
ctrl+,
to fire up the settings panelSearch for
flake8
in the search panelEnable the option
Python>Linting:Flake8 Enabled
Search for black and select
black
from the dropdown calledPython>Formatting:Provider
Doing the above will set flake8
and black
to lint and format your script on a project basis. You have to install flake8
and black
in your environment via pip install flake8
and pip install black
respectively. If you want to set them up globally and donāt want to worry about formatting ever again, you have set up their global paths. To do so:
Deactivate your environment
Install
flake8
andblack
globally viapip3 install flake8
andpip3 install black
On the terminal write
whereis flake8
andwhereis black
You should see their global paths
Now go to the
settings
and search forflake8
and paste yourflake8
path inPython āŗ Linting: Flake8 Path
optionCopy
black
path and paste them inPython āŗ Formatting: Black Path
option
Shortcuts and Keymaps š»Ā¶
VS Code is loaded with customization options and shortcuts. Default shortcuts can vary between different operating systems. However, you can always change those according to your likings. You can even adopt other editorsā keybindings into VS Code.
Changing the Default Keymaps¶
Open the command palette by pressing
ctrl+shift+p
.Type
Keyboard shortcuts
.Select
Preferences: Open Keyboard Shortcuts
. This will show you a list of all the keyboard shortcuts available to you.You can hover over a keybinding and a pencil icon should pop up.
Click on the pencil icon to add your preferred key combination and press
enter
.
Adopting Keymaps from Other Editors¶
If you are migrating from any other editors and you want to use you previous keymaps, you can do that too.
Go to the extension panel.
Type
<yourdesirededitor> keymaps
.Select and install. This should replace the default keymap with your desired one.
A Few Important Shortcuts (On Linux)¶
Although the abundance of shorcuts can be a plus,it can be intimidating for someone whoās just starting out. Hereās a short list of a few important shortcuts that appear more frequently.
ctrl+~
: Opens the integrated terminalctrl+N
: Opens a new empty filectrl+Shift+P
: Opens the command palettectrl+,
: Opens settingsctrl+B
: Toggles between shrinked and extended side panelF11
: Full screen modectrl+alt+N
: Running python codeF5
: Running python code in debugging mode
Themes šĀ¶
Here is a list of some awesome vs code themes that I have encountered over the year. Currently Iām using Cobalt2. You can use this website for searching and watching previews of the themes.
Awesome Dark Themes¶
Awesome Light Themes¶
Installing Themes¶
Installing procedure for a theme is same as installing any other extension.
From the left most stripe select extension icon
Type your desired extension name
Press install
Fonts š¹ļøĀ¶
Monospace fonts are better optimized for code readability and alignment. Here is a list of awesome coding fonts that Iāve used in the past. But I always come back to Fira Code
.
Installing Fonts¶
On Ubuntu¶
Even on same OS, installation procedure can vary between different fonts. On ubuntu, open type
fonts generally live in /usr/share/fonts/opentype/
folder.
To install
Fira Code
you can simply type:$ sudo apt install fonts-firacode
However, this often downloads older version of the font. Recently they released a sleeker version 2.0 of the font. To install that, download the font from here.. Unzip the font folder and go to
otf
folder. Then simply run:$ sudo cp -a . /usr/share/fonts/opentype/firacode
Extensions š¤Ā¶
Youāve already seen extensions like themes
, keymaps
, code runner
etc in action. These modules can take your coding experience beyond what the builtins can offer. Here is an inexhaustive list of a few awesome extensions that will help you to make your python workflow more optimized.
Code Runner: Runs code snippet or code file of many popular languages like C, C++, Java, JavaScript, PHP, Python, Perl, Ruby, Go, Lua, Groovy, PowerShell etc.
Better TOML: Syntax highlighting for
.toml
filesdocs-yaml: YAML schema validation and auto-completion
DotENV: Support for dotenv file syntax
Githistory: View git log, file history, compare branches or commits
hide-gitignored: Hide files from the file Explorer that are ignored by your workspaceās
.gitignore
filesPytest IntelliSense: Provides autocompletion for pytest
pytest-snippets: Snippet and templates for pytest
Rainbow Brackets: Provide rainbow colors for the round brackets, the square brackets and the squiggly brackets. This is particularly useful for Lisp or Clojure programmers, and of course, JavaScript, and other programmers. The isolated right bracket will be highlighted in red.
Rainbow CSV: Highlight CSV and TSV files in different colors, Run SQL-like queries
Rainbow End: This extension allows to identify keyword / end with colours.
Indent-rainbow: This extension colorizes the indentation in front of your text alternating four different colors on each step. Some may find it helpful in writing code for Nim or Python.
reStructuredText: reStructuredText language support (RST/ReST linter, preview, IntelliSense and more)
Docker: Adds syntax highlighting, commands, hover tips, and linting for Dockerfile and docker-compose files.
Bookmarks: Mark lines and jump to them
TODO Highlight: Highlight TODO, FIXME and other annotations within your code.
autoDocstring Generates python docstrings
Settings āļøĀ¶
All your settings and preferences are kept in settings.json
file. You can directly manipulate that file to set your preference locally or globally. Locally the settings file can be found in .vscode/settings.json
folder in your current project location. To see the global settings.json
, head over to $HOME/.config/Code/User/settings.json
and open it in VS Code. If you havenāt changed any of the default settings, the file should be empty or almost empty.
Syncing Your Settings & Extensions¶
You donāt want to set up VS Code from scratch every time you change your machine or do a fresh installation of your OS. In such scenarios, Settings Sync
comes to rescue. You can set it up once, sync your settings and restore the settings with a few click. This will restore all of your settings, extensions, themes and other preferences. To do so,
Search and install
Settings Sync
from the extension panelLogin with your github credentials
Press
ctrl+Shift+P
to open the command prompt and selectSync: Update/Upload Settings
option to upload your settings and save to a github gistIf you are restoring the settings to a freshly installed VS Code, just select
Sync:Download Settings
and you should see your VS Code getting restored
Shut up & Let Me Replicate Your Settings¶
If you donāt want to go through the hassle of manually installing all these extensions and like my settings. You can replicate my settings with the help of Settings Sync
too. To do so:
Go to the settings panel and search
setting sync
Find
Sync:Gist
option and replace it witheec019bccd9c49388eaf9eeaf08c19ec
(This is the gist id of my settings)Then go to command prompt and select
Sync:Download Settings
optionIt will take some time to restore all the settings and you should see a setup similar to the following screenshots:
P.S.: This settings is a modified version of Kenneth Reitzās VS Code settings. Special thanks to him open sourcing that on twitter.
Customizing the Settings According to Your Need¶
After youāve synced the above settings, you can easily change the themes, font sizes according to your liking. However, if you want to sync the settings via Settings Sync
, you have to change back the github gist id and replace that with your own id. To do so:
Go go to https://gist.github.com and find the gist name
cloudSettings
Check you url bar which should show something like this:
git.github.com/<username>/gist_id
Copy your own gist id and replace that in
Sync:Gist
(In settings)
Now you can customize the workspace with your heartās content and sync accordingly.
A few Points to Note: If you have replicated my settings, you have to:
Replace my github credentials with yours in the
settings.json
fileChange and add your own
Flake8
andBlack
path for them to work (See it here.)