course
Setting Up VSCode For Python: A Complete Guide
Why use VSCode for Python?
Virtual Studio Code (VSCode) is a perfect Integrated Development Environment for Python. It is simple and comes with built-in features that enhance the development experience. VSCode Python extensions come with powerful features like syntax autocomplete, linting, debugging, unit testing, GitOps, virtual environments, notebooks, editing tools, and the ability to customize the editor.
Key Features:
- Command Palette to access all commands by typing keywords.
- Fully customizable keyboard shortcuts.
- Jupyter extension for data science. Run Jupyter notebook within the IDE.
- Auto linting and formatting.
- Debugging and Testing.
- Git integration.
- Custom code snippets.
- Enhanced editing tools. Multi cursor selection, column selection, outline view, side-by-side preview, and search and modify.
In this tutorial, we will start by installing Python and VSCode, then run a Python script in VSCode. After that, we will customize the editor to enhance the Python development experience by installing essential extensions and learning about built-in features. In the end, we will learn about Python productivity hacks.
Python and Visual Studio Code Setup
In this part, we will learn to install Python and VSCode and run a simple Python code.
Installing Python
Downloading and installing the latest version of Python is straightforward. Go to Python.org and download the latest version for Windows. The installer is also available for Linux/Unix, macOS, and other platforms. After downloading the installer, install Python with default settings.
Image from Python.org
The most popular way of installing Python is through Anaconda Distribution. It comes with a pre-installed package and software for us to start coding without hiccups. It is available for Windows, macOS, and Linux operating systems.
Image from Anaconda
After installing Python on our operating system, check whether it is properly working by typing the following command in CLI / Terminal.
python --version
Output:
Python 3.9.13
Other Python installation methods
We can also install Python using various CLI tools or through the Windows store.
You can check out our full guide on how to install Python for more details. Similarly, our interactive Introduction to Python course helps you master the basics of Python syntax, lists, functions, packages, and Numpy.
Installing VSCode
Installing VSCode is super simple. Download and install the stable build from the official website. The installer is available for all kinds of operating systems, including web browsers.
Image from Visual Studio Code
Other VSCode installation methods
We can install using Microsoft store, Snap Store, and multiple CLI tools for Windows, Linux, and macOS.
Running Python in VSCode
After installing Python and VSCode, it is time to write a simple code and run the Python file within the IDE.
Create a new file
At start, you will see the welcome note. Ignore that and go to File > New Text File or use the keyboard shortcut Ctrl + N to create a new file. After that, write a simple print expression to display “Hello World.”
Save Python file
Save the file using Ctrl + S. Select the file directory and type the file name. Make sure to add `.py` at the end of the file name.
Select the interpreter
To run the Python file, we need to select the Python interpreter. By default, the Anaconda environment comes with Python version 3.9.13.
Run a Python file
To run the Python file, simply click on the Run button on the top left, as shown in the image. It will initialize the terminal and run the Python file to display the output.
You can also type python test.py in the terminal to run the file present in the current directory.
Installing Essential VSCode Python Extensions
The VSCode’s Python extensions will provide us with the helping functionalities for code editing, docstrings, linting, formatting, debugging, testing, and environment selection.
How to install a VSCode Extension
Click on the box icon on the activity bar or use a keyboard shortcut: Ctrl + Shift + X to open the extension panel. Type any keyword in the search bar to explore all kinds of extensions.
Install VSCode Python extension
In our case, we will type Python and install the Python extension by clicking on the install button, as shown above.
List of Essential Python Extensions
1. Python
The Python extension automatically installs Pylance, Jupyter, and isort extensions. It comes with a complete collection of tools for Data Science, web development, and software engineering.
Key Features:
Python extension comes with IntelliSense, linting, debugging, code navigation, code formatting, refactoring, variable explorer, and test explorer.
- IntelliSense (code autocomplete)
- Linting (Pylint, Flake8)
- Code formatting (black, autopep)
- Debugging
- Testing (unittest, pytest)
- Jupyter Notebooks
- Environments (venv, pipenv, conda)
- Refactoring
2. Indent-rainbow
Indent-rainbow extensions provide us with a multilevel colorized indentation for improved code readability. We get alternating colors on each step, and it helps us avoid common indentation errors.
3. Python Indent
Python Indent extension helps us with creating indentations. By pressing the Enter key, the extension will parse the Python file and determine how the next line should be indented. It is a time saver.
4. Jupyter Notebook Renderers
Jupyter Notebook Renderers is part of the Jupyter extension pack. It helps us render plotly, vega, gif, png, svg, and jpeg output.
5. autoDocstring
The autoDocstring extension helps us quickly generate docstring for Python functions. By typing triple quotes """ or ''' within the function, we can generate and modify docstring. Learn more about doc strings by following our Python Docstrings tutorial.
Note: Most Python development extensions and features come with Python extensions.
Visual Studio Code Python for Data Science
Visual Studio Code allows users to simply run the data science code in Jupyter Notebook. We can run the cell and visualize the result within VSCode. It supports all kinds of programming languages and comes with built-in features to mimic the browser-based Jupyter notebook that we all love.
Learn more about Jupyter Notebooks by reading our How to use Jupyter Notebook tutorial.
To use the Jupyter notebook extension, we need to first install a Jupyter notebook.
pip install jupyterlab
Or
pip install notebook
Note: Jupyter Notebook and Jupyter Lab come with Anaconda Distribution, so we don't have to install anything.
Install Jupyter Extension
After that, install the Jupyter extension from the Visual Studio marketplace.
To create a Jupyter notebook file, we can either create a new file with .ipynb extension or access the command palette (Ctrl+Shift+P) and select Jupyter: Create New Jupyter Notebook.
Pick the Ipython Kernel
To initialize the Jupyter server, we need to select the kernel by clicking on the kernel picker in the top right of the notebook, as shown in the image.
Note: By default, Anaconda comes with Python version 3.9.13. You can download the latest version of Python 3.11, but it won’t support all packages.
Run the Jupyter cell
Write a print expression to display “Hello World” and press the run button.
Add another cell
You can use the B key or click on + Code to add a new cell and run the cell with Ctrl + ⤶ Enter. You can learn about Jupyter keyboard shortcuts on defkey.
For R language users, we have got a Notebooks for R tutorial. You will learn to use R in a Jupyter Notebook and useful features.
Note: if you are looking for a hassle-free way of using Jupyter Notebook, then try DataCamp's DataLab. It comes with essential Python libraries, a pre-build environment, and it supports various database integration.
DataLab
Skip the installation process and experiment with data science code in your browser with DataLab, DataCamp's AI-powered notebook.
Configuring Linting and Formatting in VSCode
Linting
Linting highlights the problems in the Python source code and provides us with suggestions. It generally highlights syntactical and stylistic issues. Linting helps you identify and correct coding issues that can lead to errors.
You can select the linting method by selecting Python: Select Linter command in the command palette (Ctrl+Shift+P). You can also manually enable the linting method in settings.
Select linting method
In our case, we have selected the flake8 method. You can also review the list of available linting methods.
- Enable/ Disable Linting: select Python: Enable/Disable Linting in command palette.
- Run Linting: command palette (Ctrl+Shift+P) > Python: Run Linting.
Fixing the error
After running the Python linter, you will see the issues with the suggestions.
Note: Enabling a different linter will prompt you to install the required Python package.
Formatting
Formatting makes code readable. It follows specific rules for line spacing, indents, spacing around operators, and closing brackets. The Python extension supports three Python formatting methods: autopep8, black, or yapf.
By reading about PEP-8: Python Naming Conventions & Code Standards, you can learn Python's style guide and formatting rules.
Select the Python formatter
To access the formatting option, we have to open the settings panel by going to Preferences -> Settings or using the keyboard shortcut: Ctrl +,. After that, type "python formatting provider" in the search bar and select "black" from the dropdown menu.
Configure Python formatter
For formatting the Python file on save, we have to search for format on save in the Settings and enable the Editor: Format on Save option.
Popular linting and formatting tools
Use this table as a reference to know which tools to install for your use case.
Tool name | Features | Benefits |
---|---|---|
Pylint | Checks for errors, enforces coding standards, and detects code smells. | Helps maintain a high code quality by identifying errors early. |
Flake8 | Combines PyFlakes, pycodestyle, and McCabe for comprehensive linting. | Ensures adherence to PEP 8 and improves code readability. |
Black | Automatically formats Python code to be consistent and readable. | Saves time and effort with consistent formatting, adhering to PEP 8. |
autopep8 | Automatically formats Python code to conform to the PEP 8 style guide. | Quick formatting tool that ensures code style compliance. |
yapf | Formats Python code based on Google's style guide. | Offers a highly configurable formatting tool based on style preferences. |
Debugging and Testing in VSCode
Debugging
The Python extension comes with Debugging for all kinds of applications like multi-threaded, web, and remote applications. We can set breakpoints, inspect data, and run programs step by step.
Select a debug configuration
Launch the debug tab by clicking on the debug icon on the action bar or by using the keyboard shortcut Ctrl + Shift +D. To customize Debug options, click on create a launch.json file and select Python File.
Debug Panel
Run the Debug by clicking on the blue button Run and Debug, and it will run the Python file and show us the Variables, Watch, Call Stack, and breakpoints.
Quick debug
For quick debugging, you can always click on the down arrow beside the Run button and select Debug Python File.
Testing
The Python extension supports unittest and pytest testing frameworks. Instead of reading the test results in a terminal, you can review and resolve the issues within the Testing tab in an active bar.
Configure Python tests
After clicking on the Testing button, we will click on the Configure Python Tests button and select the testing framework. Usually, VSCode automatically detects the framework and displays all the tests in a tree view.
Learn about Python unit testing, implementing Python's pytest testing framework by following our how to use pytest for unit testing tutorial.
Note: The testing example that we are using is from Visual Studio Code official documentation.
Run the unittest
We can run the Unit test by clicking on the Run Test button in the Testing tab and analyzing the results.
As we can observe, 1 of 2 tests have passed, and it has displayed the reasoning behind the failed result. VSCode testing is highly interactive and user-friendly.
Git Integration
VSCode comes with built-in Git integration. No more writing Git commands on terminals. Git integration provides a user-friendly GUI and helpful functions for diff, views, staging, branching, committing, merge, and more.
Check out our Git Cheat Sheet to learn about the various Git commands and functionalities.
Note: To enable Git integration, you need to install Git from official site.
Initializing Git
We can access it through the action bar or by using the keyboard shortcut: Ctrl + Shift + G. Before we start committing, we need to initialize the repository.
Git Commit
After that, add and commit the changes with the message. It is that simple.
Create a GitHub repository and push the code
You can even create a GitHub repository and push your code to a remote server by logging into your GitHub account.
Private GitHub repository
We have created a GitHub private repository of Python files and folders.
You can now simply commit and push the changes to the remote server without leaving the VSCode.
Follow our Github and Git tutorial to learn everything about Git and GitHub.
AI-Powered Features
To enhance your coding experience in VSCode, consider enabling AI-powered code completion features. One prominent tool is GitHub Copilot, an AI pair programmer that assists by suggesting code snippets and entire functions as you type.
To enable GitHub Copilot in VSCode:
- Install the GitHub Copilot extension:
- Search for "GitHub Copilot".
- Click Install on the GitHub Copilot extension.
- Sign in to GitHub:
- After installation, you'll be prompted to sign in to your GitHub account.
- Follow the on-screen instructions to authenticate.
- Configure settings:
- Access settings by clicking the gear icon in the lower-left corner and selecting Settings.
- Search for "Copilot" to adjust preferences, such as enabling or disabling specific features.
Tips and Tricks for Efficient Python Development in VSCode
VSCode comes with awesome Python development features and extensions. We can customize them to our needs and improve the productivity. In this section, we will learn about tips and tricks for efficient Python development.
- Getting started: Help > Get Started. Learn about VSCode’s customization and features by following guided tutorials.
- Command Palette: access entire all available commands by using the Keyboard shortcut: Ctrl+Shift+P. By writing keywords, we can access specific commands.
- Keyboard shortcuts: better than command palettes. We can modify keyboard shortcuts or memorize them by using keyboard reference sheets. It will help us access the commands directly, instead of searching with the keyword.
- Command line: launch the VSCode editor through the command line interface by typing `code .`. We can also customize how the editor is launched by adding additional arguments.
- Errors and warnings: quick jump to errors and warnings in a project by using the keyboard shortcut: Ctrl+Shift+M. We can also cycle through the error with F8 or Shift+F8.
- Customization: VSCode allows us to customize themes, keyboard shortcuts, JSON validation, debugging settings, fonts, and many more. It is a fully customizable IDE.
- Extensions: other Python extensions improve our development experience. Look for popular extensions on the Visual Studio Marketplace.
- Multi cursor selection: is a lifesaver. Add cursors at arbitrary positions by using Alt+Click. It will allow us to modify multiple lines of code at once. We can also use Ctrl+Shift+L to modify all occurrences of the current selection.
- Search and modify: this is the best tool for searching and modifying multiple expressions at once. We can also rename the symbol by selecting the symbol and typing F2.
- Git integration: allows us to perform all Git-related tasks within IDE. It provides an easy-to-use GUI for diff, views, staging, branching, committing, merging, and more.
- Code Snippets: is our best friend. Just like Autohotkey, we are creating templates for repeating code patterns. To create a custom code snippet, select File > Preferences > Configure User Snippets and then select the language.
- GitHub Copilot: is a winner extension for all kinds of development. It enhances the coding experience with artificial intelligence (AI) by suggesting lines of code or entire functions.
Bonus: sync your settings by logging into your GitHub account. It will sync your settings across all of the machines.
Conclusion
VSCode is not just a code editor. It is a complete ecosystem for efficient Python development. It provides us with shortcuts, Commands Palette, IntelliSense, linting, formatting, debugging, formatting, Git integrations, Jupyter notebook, third-party extensions, and a fully customizable development experience.
VSCode is highly recommended to beginners who are learning the basics of Python and data science. Complete Data Scientist with a Python career track to become a master in Python and data science. The career track consists of 25 courses and six projects to prepare you to become a professional data scientist.
Become a Python Developer
FAQs
How do I configure VSCode to automatically activate a virtual environment when opening a project?
You can configure VSCode to automatically activate a virtual environment by adding a .vscode/settings.json
file in your project folder with the following content:
{
"python.pythonPath": "<path-to-your-virtual-environment>/bin/python"
}
Can I use VSCode for remote development on a server with Python?
Yes, you can use the Remote - SSH extension in VSCode to connect to a remote server. Once connected, you can access files and run Python code as if it were local.
What are some recommended extensions for Python data visualization in VSCode?
For data visualization, extensions like Plotly for Visual Studio Code and Jupyter Notebook Renderers can enhance your experience by providing interactive plots and rendering capabilities.
How can I configure VSCode to use a specific Python interpreter for different projects?
You can specify a Python interpreter for each project by selecting the interpreter in the Command Palette (Ctrl+Shift+P) using the command "Python: Select Interpreter". This setting is saved in the project's .vscode/settings.json
.
Is there a way to preview Python documentation or docstrings within VSCode?
Yes, you can use the "Peek Definition" feature by right-clicking on a function or method to view its documentation or docstring inline without navigating away from your current code.
How can I optimize VSCode performance for large Python projects?
To improve performance, consider disabling extensions that are not in use, increase the memory limit for TypeScript server if needed, and ensure that large files or folders are excluded from search and linting using the files.exclude
and files.watcherExclude
settings.
Can I use VSCode to collaborate in real-time with other Python developers?
Yes, you can use the Live Share extension which allows multiple developers to collaborate in real-time on the same codebase, including sharing debugging sessions and server ports.
How do I set up VSCode to format Python code on save using Black?
To set up VSCode to format Python code using Black, go to Settings and search for "Python formatting provider", select "black", and ensure "Editor: Format On Save" is enabled.
Are there any VSCode extensions that can assist with learning Python syntax?
The Python extension already provides significant help with syntax highlighting and IntelliSense. Additionally, you can use the Code Runner extension to quickly run Python snippets and see the results, which can aid in learning.
How can I troubleshoot issues with Python linting in VSCode?
If linting is not working as expected, ensure the linter is installed in your Python environment. You can also check the Output panel (View > Output) and select "Python" from the dropdown to see any error messages. Additionally, verify that the correct linter is selected in the settings.
As a certified data scientist, I am passionate about leveraging cutting-edge technology to create innovative machine learning applications. With a strong background in speech recognition, data analysis and reporting, MLOps, conversational AI, and NLP, I have honed my skills in developing intelligent systems that can make a real impact. In addition to my technical expertise, I am also a skilled communicator with a talent for distilling complex concepts into clear and concise language. As a result, I have become a sought-after blogger on data science, sharing my insights and experiences with a growing community of fellow data professionals. Currently, I am focusing on content creation and editing, working with large language models to develop powerful and engaging content that can help businesses and individuals alike make the most of their data.
Learn more about Python with these courses!
course
Exploratory Data Analysis in Python
course
Python Toolbox
blog
How to Install Python on macOS and Windows
tutorial
Python Setup: The Definitive Guide
J. Andrés Pizarro
15 min
tutorial
Python Tutorial for Beginners
tutorial
Python Backend Development: A Complete Guide for Beginners
Oluseye Jeremiah
26 min
tutorial
Introduction to Python IDLE Tutorial
tutorial
Mastering PyCharm Tutorial
DataCamp Team
19 min