Code Actions
Code Actions (also known as Quick Fixes) are provided to help fix issues when there are warnings in your code. These helpful hints are displayed in the editor left margin as a lightbulb (💡). Select the light bulb to display Code Action options. These Code Action can come from extensions such as Python, Pylance, or VS Code itself. For more information about Code Actions, see Python Quick Fixes.
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 Workspace. It comes with essential Python libraries, a pre-build environment, and it supports various database integration.
Free Python and Data Science lessons
NASA-inspired lessons
This learning path enables students to use Python to explore doing analyses and projects inspired from real-world problems faced by National Aeronautics and Space Administration (NASA) scientists. View full details of the lessons under NASA-inspired Lessons.
Learn Python with Over The Moon
These space-themed lessons were inspired by the Netflix film, Over the Moon, and will introduce students to data science, machine learning, and artificial intelligence using Python and Azure. View full details on Learn Python with Over The Moon.
Wonder Woman-inspired lessons
Give an introduction to Python with “Wonder Woman 1984”-inspired lessons that help students learn about the basics like conditionals and variables. Get full lesson details under Learn Python with Wonder Woman.
Python in Notebooks
Learn the basics of Python. View the full lesson at Write basic Python in Notebooks in Visual Studio Code.
Set up your Python beginner development environment
A step-by-step guide to installing and setting up your Python and VS Code environment. View the full lesson at Set up your Python beginner development environment with Visual Studio Code.
Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Python Development in Visual Studio Code (Setup Guide)
One of the coolest code editors available to programmers, Visual Studio Code, is an open-source, extensible, light-weight editor available on all platforms. It’s these qualities that make Visual Studio Code from Microsoft very popular, and a great platform for Python development.
In this article, you’ll learn about Python development in Visual Studio Code, including how to:
- Install Visual Studio Code
- Discover and install extensions that make Python development easy
- Write a straightforward Python application
- Learn how to run and debug existing Python programs in VS Code
- Connect Visual Studio Code to Git and GitHub to share your code with the world
We assume you are familiar with Python development and already have some form of Python installed on your system (Python 2.7, Python 3.6/3.7, Anaconda, or others). Screenshots and demos for Ubuntu and Windows are provided. Because Visual Studio Code runs on all major platforms, you may see slightly different UI elements and may need to modify certain commands.
If you already have a basic VS Code setup and you’re hoping to dig deeper than the goals in this tutorial, you might want to explore some advanced features in VS Code.
Free Bonus: 5 Thoughts On Python Mastery, a free course for Python developers that shows you the roadmap and the mindset you’ll need to take your Python skills to the next level.
Next steps
To learn how to build web apps with popular Python web frameworks, see the following tutorials:
There is then much more to explore with Python in Visual Studio Code:
- Python profile template – Create a new profile with a curated set of extensions, settings, and snippets
- Editing code – Learn about autocomplete, IntelliSense, formatting, and refactoring for Python.
- Linting – Enable, configure, and apply a variety of Python linters.
- Debugging – Learn to debug Python both locally and remotely.
- Testing – Configure test environments and discover, run, and debug tests.
- Settings reference – Explore the full range of Python-related settings in VS Code.
- Deploy Python to Azure App Service
- Deploy Python to Container Apps
Quick Start Guide for Python in VS Code
The Python extension makes Visual Studio Code an excellent Python editor, works on any operating system, and is usable with a variety of Python interpreters.
Get started by installing:
- VS Code
- A Python Interpreter (any actively supported Python version)
- Python extension from the VS Code Marketplace
To further customize VS Code for Python, you can leverage the Python profile template, automatically installing recommended extensions and settings. For Data Science projects, consider using the Data Science profile template.
Installing and Configuring Visual Studio Code for Python Development
Installing Visual Studio Code is very accessible on any platform. Full instructions for Windows, Mac, and Linux are available, and the editor is updated monthly with new features and bug fixes. You can find everything at the Visual Studio Code website:
In case you were wondering, Visual Studio Code (or VS Code for short) shares almost nothing other than a name with its larger Windows-based namesake, Visual Studio.
Note: To learn how to set up VS Code as part of a full Python coding environment on a Windows machine, check out this comprehensive guide.
Visual Studio Code has built-in support for multiple languages and an extension model with a rich ecosystem of support for others. VS Code is updated monthly, and you can keep up to date at the Microsoft Python blog. Microsoft even makes the VS Code GitHub repo available for anyone to clone and contribute. (Cue the PR flood.)
The VS Code UI is well documented, so I won’t rehash it here:
Extensions for Python Development
As stated above, VS Code supports development in multiple programming languages through a well-documented extension model. The Python extension enables Python development in Visual Studio Code, with the following features:
- Support for Python 3.4 and higher, as well as Python 2.7
- Code completion with IntelliSense
- Linting
- Debugging support
- Code snippets
- Unit testing support
- Automatic use of conda and virtual environments
- Code editing in Jupyter environments and Jupyter Notebooks
Visual Studio Code extensions cover more than just programming language capabilities:
-
Keymaps allow users already familiar with Atom, Sublime Text, Emacs, Vim, PyCharm, or other environments to feel at home.
-
Themes customize the UI whether you like coding in the light, dark, or something more colorful.
-
Language packs provide a localized experience.
Here are some other extensions and settings I find useful:
-
GitLens provides tons of useful Git features directly in your editing window, including blame annotations and repository exploration features.
-
Auto save is easily turned on by selecting
File, Auto Save
from the menu. The default delay time is 1000 milliseconds, which is also configurable. -
Settings Sync allows you to synchronize your VS Code settings across different installations using GitHub. If you work on different machines, this helps keep your environment consistent across them.
-
Docker lets you quickly and easily work with Docker, helping author
Dockerfile
and
docker-compose.yml
, package and deploy your projects, and even generate the proper Docker files for your project.
Of course, you may discover other useful extensions as you use VS Code. Please share your discoveries and settings in the comments!
Discovering and installing new extensions and themes is accessible by clicking on the Extensions icon on the Activity Bar. You can search for extensions using keywords, sort the results numerous ways, and install extensions quickly and easily. For this article, install the Python extension by typing
python
in the Extensions item on the Activity Bar, and clicking Install:
You can find and install any of the extensions mentioned above in the same manner.
Visual Studio Code Configuration Files
One important thing to mention is that Visual Studio Code is highly configurable through user and workspace settings.
User settings are global across all Visual Studio Code instances, while workspace settings are local to the specific folder or project workspace. Workspace settings give VS Code tons of flexibility, and I call out workspace settings throughout this article. Workspace settings are stored as
.json
files in a folder local to the project workspace called
.vscode
.
Manage extensions
VS Code makes it easy to manage your extensions. You can install, disable, update, and uninstall extensions through the Extensions view, the Command Palette (commands have the Extensions: prefix) or command-line switches.
List installed extensions
By default, the Extensions view will show the extensions you currently have installed, and all extensions that are recommended for you. You can use the Extensions: Focus on Installed View command, available in the Command Palette (⇧⌘P (Windows, Linux Ctrl+Shift+P)) or in the More Actions (
...
) dropdown menu > Views > Installed, to clear any text in the search box and show the list of all installed extensions, which includes those that have been disabled.
Uninstall an extension
To uninstall an extension, select the Manage gear button at the right of an extension entry and then choose Uninstall from the dropdown menu. This will uninstall the extension and prompt you to reload VS Code.
Disable an extension
If you don’t want to permanently remove an extension, you can instead temporarily disable the extension by clicking the gear button at the right of an extension entry. You can disable an extension globally or just for your current Workspace. You will be prompted to reload VS Code after you disable an extension.
If you want to quickly disable all installed extensions, there is a Disable All Installed Extensions command in the Command Palette and More Actions (
...
) dropdown menu.
Extensions remain disabled for all VS Code sessions until you re-enable them.
Enable an extension
Similarly if you have disabled an extension (it will be in the Disabled section of the list and marked Disabled), you can re-enable it with the Enable or Enable (Workspace) commands in the dropdown menu.
There is also an Enable All Extensions command in the More Actions (
...
) dropdown menu.
Extension auto-update
VS Code checks for extension updates and installs them automatically. After an update, you will be prompted to reload VS Code. If you’d rather update your extensions manually, you can disable auto-update with the Disable Auto Updating Extensions command that sets the
extensions.autoUpdate
setting to
false
.
If you don’t want VS Code to even check for updates, you can set the
extensions.autoCheckUpdates
setting to false.
Update an extension manually
If you have extensions auto-update disabled, you can quickly look for extension updates by using the Show Outdated Extensions command that uses the
@updates
filter. This will display any available updates for your currently installed extensions.
Select the Update button for the outdated extension. The update will be installed, and you’ll be prompted to reload VS Code. You can also update all your outdated extensions at one time with the Update All Extensions command.
If you also have automatic checking for updates disabled, you can use the Check for Extension Updates command to check which of your extensions can be updated.
Hướng dẫn lập trình Python với Visual Studio Code
Bước 1: Cài đặt Python và VSCode
Cài đặt Python:
- Truy cập trang chính thức của Python: https://www.python.org/.
- Tải và cài đặt phiên bản Python mới nhất cho hệ điều hành của bạn. Trong quá trình cài đặt, hãy chọn tùy chọn “Add Python to PATH” để thêm Python vào biến môi trường.
Cài đặt Visual Studio Code:
- Truy cập trang chính thức của VSCode: https://code.visualstudio.com/.
- Tải và cài đặt phiên bản mới nhất cho hệ điều hành của bạn.
Bước 2: Cài đặt Extension Python cho VSCode
- Mở VSCode.
-
Trong thanh bên trái, chọn biểu tượng “Extensions” (hoặc nhấn
Ctrl+Shift+X
). - Tìm kiếm “Python” trong ô tìm kiếm.
- Chọn extension “Python” được phát triển bởi Microsoft và nhấn nút “Install”.
Bước 3: Tạo và Chạy một File Python
- Mở VSCode.
- Chọn “File” > “New File” để tạo một file mới.
-
Lưu file với đuôi
.py
, ví dụ:
hello.py
. -
Viết mã Python vào file. Ví dụ:pythonCopy code
print("Hello, World!")
- Chọn “View” > “Terminal” để mở terminal tích hợp tại đáy của VSCode.
-
Gõ lệnh sau để chạy script Python:bashCopy code
python hello.py
hoặcbashCopy code
python3 hello.py
Bước 4: Debugging
- Đặt breakpoints bằng cách nhấn vào cạnh số dòng code bạn muốn dừng lại.
-
Nhấn
F5
để bắt đầu chế độ debug. Bạn cũng có thể sử dụng các biểu tượng debug trên thanh công cụ.
Bước 5: Cài đặt Thêm (Optional)
-
Python Docstring Generator:
- Cài đặt extension “Python Docstring Generator” để tự động tạo docstrings cho hàm và phương thức.
-
Pylint hoặc flake8:
- Cài đặt extension “Pylint” hoặc “flake8” để kiểm tra mã nguồn Python và cải thiện chất lượng mã.
-
Jupyter (Nếu cần):
- Cài đặt extension “Jupyter” để hỗ trợ Jupyter Notebooks trong VSCode.
Bước 6: Cập nhật Extension và VSCode
Hãy thường xuyên kiểm tra và cập nhật các extension Python và VSCode để đảm bảo bạn sử dụng phiên bản mới nhất với các tính năng và sửa lỗi.
Install an extension
To install an extension, select the Install button. Once the installation is complete, the Install button will change to the Manage gear button.
Find and install an extension
For example, let’s install the popular TODO Highlight extension. This extension highlights text like ‘TODO:’ and ‘FIXME:’ in your source code so you can quickly find undone sections.
In the Extensions view (⇧⌘X (Windows, Linux Ctrl+Shift+X)), type ‘todo’ in the search box to filter the Marketplace offerings to extensions with ‘todo’ in the title or metadata. You should see the TODO Highlight extension in the list.
An extension is uniquely identified by its publisher and extension IDs. If you select the TODO Highlight extension, you will see the Extension details page, where you can find the extension ID, in this case,
wayou.vscode-todo-highlight
. Knowing the extension ID can be helpful if there are several similarly named extensions.
Select the Install button, and VS Code will download and install the extension from the Marketplace. When the installation is complete, the Install button will be replaced with a Manage gear button.
To see the TODO Highlight extension in action, open any source code file and add the text ‘TODO:’ and you will see the text highlighted.
The TODO Highlight extension contributes the commands, TODO-Highlight: List highlighted annotations and TODO-Highlight: Toggle highlight, that you can find in the Command Palette (⇧⌘P (Windows, Linux Ctrl+Shift+P)). The TODO-Highlight: Toggle highlight command lets you quickly disable or enable highlighting.
The extension also provides settings for tuning its behavior, which you can find in the Settings editor (⌘, (Windows, Linux Ctrl+,)). For example, you might want the text search to be case insensitive and you can uncheck the Todohighlight: Is Case Sensitive setting.
If an extension doesn’t provide the functionality you want, you can always Uninstall the extension from the Manage button context menu.
This has been just one example of how to install and use an extension. The VS Code Marketplace has thousands of extensions supporting hundreds of programming languages and tasks. Everything from full featured language support for Java, Python, Go, and C++ to simple extensions that create GUIDs, change the color theme, or add virtual pets to the editor.
Extension details
On the extension details page, you can read the extension’s README and review the extension’s:
- Feature Contributions – The extension’s additions to VS Code such as settings, commands and keyboard shortcuts, language grammars, debugger, etc.
- Changelog – The extension repository CHANGELOG if available.
- Dependencies – Lists if the extension depends on any other extensions.
If an extension is an Extension Pack, the Extension Pack section will display which extensions will be installed when you install the pack. Extension Packs bundle separate extensions together so they can be easily installed at one time.
Extensions view filter and commands
You can filter the Extensions view with the Filter Extensions context menu.
There are filters to show:
- The list of outdated extensions that can be updated
- The list of currently enabled/disabled extensions
- The list of recommended extensions based on your workspace
- The list of globally popular extensions
You can sort the extension list by Install Count, Rating, Name, Published Date, or Updated Date in either ascending or descending order. You can learn more about extension search filters below.
You can run additional Extensions view commands via the
...
View and More Actions button.
Through this context menu you can control extension updates, enable or disable all extensions, and use the Extension Bisect utility to isolate problematic extension behavior.
Search for an extension
You can clear the Search box at the top of the Extensions view and type in the name of the extension, tool, or programming language you’re looking for.
For example, typing ‘python’ will bring up a list of Python language extensions:
If you know the exact identifier for an extension you’re looking for, you can use the
@id:
prefix, for example
@id:vue.volar
. Additionally, to filter or sort results, you can use the filter and sort commands, detailed below.
Run Python code
To experience Python, create a file (using the File Explorer) named
hello.py
and paste in the following code:
print("Hello World")
The Python extension then provides shortcuts to run Python code using the currently selected interpreter (Python: Select Interpreter in the Command Palette). To run the active Python file, click the Run Python File in Terminal play button in the top-right side of the editor.
You can also run individual lines or a selection of code with the Python: Run Selection/Line in Python Terminal command (Shift+Enter). If there isn’t a selection, the line with your cursor will be run in the Python Terminal. An identical Run Selection/Line in Python Terminal command is available on the context menu for a selection in the editor. The same terminal will be used every time you run a selection or a line in the terminal/REPL, until that terminal is closed. The same terminal is also used for Run Python File in Terminal. If that terminal is still running the REPL, you should exit the REPL (
exit()
) or switch to a different terminal before running a Python file.
The Python extension automatically removes indents based on the first non-empty line of the selection, shifting all other lines left as needed.
The command opens the Python Terminal if necessary; you can also open the interactive REPL environment directly using the Python: Start REPL command that activates a terminal with the currently selected interpreter and then runs the Python REPL.
For a more specific walkthrough and other ways of running code, see the run code tutorial.
Python Extension Pack
Unsure which extensions to recommend to your students? You can point your students to the Python Education Extension Pack that contains essential and helpful extensions for the classroom. You can download the extension pack from the VS Code Marketplace:
The extension pack contains:
- Python for basic Python functionality like compiling, debugging support, linting, Jupyter Notebooks, unit tests, and more.
- Live Share to enable real-time collaboration.
- Remote – SSH to work on remote projects (for example, to access lab machines) through SSH with full VS Code functionality.
- Markdown+Math for full LaTeX support in Markdown.
- Python Test Explorer for Visual Studio Code to visualize and run Python tests in the side bar.
- Code Runner to run snippets (selected code) and single files of any code with a single click.
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.
Enhance completions with AI
GitHub Copilot is an AI-powered code completion tool that helps you write code faster and smarter. You can use the GitHub Copilot extension in VS Code to generate code, or to learn from the code it generates.
GitHub Copilot provides suggestions for languages beyond Python and a wide variety of frameworks, including JavaScript, TypeScript, Ruby, Go, C# and C++.
You can learn more about how to get started with Copilot in the Copilot documentation.
Extensions view filters
The Extensions view search box supports filters to help you find and manage extensions. You may have seen filters such as
@installed
and
@recommended
if you used the commands Show Installed Extensions and Show Recommended Extensions. Also, there are filters available to let you sort by popularity or ratings and search by category (for example ‘Linters’) and tags (for example ‘node’). You can see a complete listing of all filters and sort commands by typing in the extensions search box and navigating through the suggestions:
Here are the Extensions view filters:
-
@builtin
– Show extensions that come with VS Code. Grouped by type (Programming Languages, Themes, etc.). -
@disabled
– Show disabled installed extensions. -
@installed
– Show installed extensions. -
@outdated
– Show outdated installed extensions. A newer version is available on the Marketplace. -
@enabled
– Show enabled installed extensions. Extensions can be individually enabled/disabled. -
@recommended
– Show recommended extensions. Grouped as Workspace specific or general use. -
@category
– Show extensions belonging to specified category. Below are a few of supported categories. For a complete list, type
@category
and follow the options in the suggestion list:-
@category:themes
-
@category:formatters
-
@category:linters
-
@category:snippets
-
These filters can be combined as well. For example: Use
@installed @category:themes
to view all installed themes.
If no filter is provided, the Extensions view displays the currently installed and recommended extensions.
Sorting
You can sort extensions with the
@sort
filter, which can take the following values:
-
installs
– Sort by Marketplace installation count, in descending order. -
name
– Sort alphabetically by extension name. -
publishedDate
– Sort by extension published date. -
rating
– Sort by Marketplace rating (1-5 stars), in descending order. -
updateDate
– Sort by extension last update name.
Categories and tags
Extensions can set Categories and Tags describing their features.
You can filter on category and tag by using
category:
and
tag:
.
Supported categories are:
[Azure, Data Science, Debuggers, Education, Extension Packs, Formatters, Keymaps, Language Packs, Linters, Machine Learning, Notebooks, Others, Programming Languages, SCM Providers, Snippets, Testing, Themes, Visualization]
. They can be accessed through IntelliSense in the extensions search box:
Note that you must surround the category name in quotes if it is more than one word (for example,
category:"SCM Providers"
).
Tags may contain any string and are not provided by IntelliSense, so review the Marketplace to find helpful tags.
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.
A Deep Dive into the Phi-2 Model
Python List Size: 8 Different Methods for Finding the Length of a List in Python
An End-to-End ML Model Monitoring Workflow with NannyML in Python
Bex Tuychiev
15 min
Autocomplete and IntelliSense
The Python extension supports code completion and IntelliSense using the currently selected interpreter. IntelliSense is a general term for a number of features, including intelligent code completion (in-context method and variable suggestions) across all your files and for built-in and third-party modules.
IntelliSense quickly shows methods, class members, and documentation as you type. You can also trigger completions at any time with ⌃Space (Windows, Linux Ctrl+Space). Hovering over identifiers will show more information about them.
Recommended extensions
You can see a list of recommended extensions using Show Recommended Extensions, which sets the
@recommended
filter. Extension recommendations can either be:
- Workspace Recommendations – Recommended by other users of your current workspace.
- Other Recommendations – Recommended based on recently opened files.
See the section below to learn how to contribute recommendations for other users in your project.
Ignoring recommendations
To dismiss a recommendation, select on the extension item to open the Details page and then select the Manage gear button to display the context menu. Select the Ignore Recommendation menu item. Ignored recommendations will no longer be recommended to you.
Data and telemetry
The Microsoft Python Extension for Visual Studio Code collects usage
data and sends it to Microsoft to help improve our products and
services. Read our
privacy statement to
learn more. This extension respects the
telemetry.enableTelemetry
setting which you can learn more about at
https://code.visualstudio.com/docs/supporting/faq#_how-to-disable-telemetry-reporting.