Visual Studio Code is an exceptional code editor developed by Microsoft, has gained immense popularity among programmers due to its open-source nature, lightweight design, and cross-platform compatibility. It’s an ideal platform for Python development.
In this tutorial, we’ll delve into Python development using Visual Studio Code by covering the following topics:
- Installing Visual Studio Code
- Exploring and installing extensions that simplify Python development
- Crafting a simple Python application
- Running and debugging existing Python programs in VS Code
- Connecting Visual Studio Code to Git and GitHub for code collaboration
We assume you have some experience with Python development and have installed a version of Python on your system.
I provide screenshots and demos for both Ubuntu and Windows. Keep in mind that Visual Studio Code runs on all major platforms, so you may encounter minor differences in UI elements or need to adjust specific commands.For those who already have a basic VS Code setup and are looking to explore more advanced features, consider researching further into VS Code’s capabilities.
Installing & Setting up Visual Studio Code for Python Development
Visual Studio Code offers easy installation across various platforms.
Comprehensive instructions for Windows, Mac, and Linux are provided, while the editor receives monthly updates featuring new functionalities and bug fixes. Visit the Visual Studio Code website to access everything you need.
[INSERT IMAGE]
You might be curious to know that Visual Studio Code (often abbreviated as VS Code) has little in common with its more extensive Windows-based counterpart, Visual Studio, aside from the name.
VS Code boasts built-in support for numerous languages, as well as a thriving ecosystem of extensions for additional language support.
With monthly updates, you can stay current by following the Microsoft Python blog.
Microsoft even opens up the VS Code GitHub repository for anyone to clone and contribute (cue the influx of pull requests).
The VS Code user interface is thoroughly documented, so there’s no need to reiterate it here.
Python Development Extensions
VS Code facilitates development in various programming languages through its robust extension model.
For example, the Python extension for Visual Studio Code enhances the development experience for Python developers by providing a wide array of features that cater to different aspects of Python development. These features are designed to improve productivity, code quality, and overall development efficiency. Some of the key features of the Python extension include:
- Compatibility: The extension supports a range of Python versions, including Python 2.7, Python 3 and above. This broad compatibility allows developers to work with legacy codebases or develop new projects using the latest Python features.
- IntelliSense code completion: IntelliSense is an intelligent code completion feature that provides context-aware suggestions as you type. This helps to speed up coding by offering relevant suggestions for variables, functions, classes, and modules, reducing the need to memorize syntax and function names.
- Linting: The Python extension supports various linters that help you identify potential errors, stylistic issues, or deviations from coding standards in your code. This feature helps to maintain code quality and consistency across your projects.
- Debugging support: The extension provides comprehensive debugging support, including setting breakpoints, examining variables, monitoring expressions, and navigating the call stack. This allows you to quickly identify and fix issues in your code.
- Code snippets: Code snippets are pre-defined pieces of code that can be inserted into your code with just a few keystrokes. The Python extension includes a collection of useful code snippets that can help you write code faster and more efficiently.
- Unit testing support: The extension supports various unit testing frameworks, including unittest, pytest, and nose. This allows you to write and run tests for your code, ensuring its reliability and correctness.
- Seamless integration with conda and virtual environments: The Python extension integrates with both conda and virtual environments, allowing you to manage dependencies and switch between different Python environments easily.
- Code editing in Jupyter environments and Jupyter Notebooks: The Python extension provides support for working with Jupyter environments and Jupyter Notebooks, allowing you to write, run, and debug code in an interactive, notebook-style interface. This feature is particularly useful for data scientists and researchers who need a flexible environment for experimentation and analysis.
These features, combined with the power and flexibility of Visual Studio Code, make it an excellent choice for Python developers seeking a powerful and customizable development environment.
VS Code Available Extensions
Visual Studio Code offers a wealth of extensions and settings to enhance your development experience. Here are some popular extensions and settings that can be helpful for developers working with various technologies and tools:
- GitLens: GitLens is a powerful extension that integrates an array of Git features directly into your editing window. It provides useful functionalities such as blame annotations, repository exploration tools, commit history tracking, and in-line code changes. With GitLens, you can easily visualize code authorship, view commit details, and navigate through the history of a file or project, all within the VS Code interface.
- Auto Save: The Auto Save feature in VS Code automatically saves your changes after a specified delay, ensuring you don’t lose any work due to unexpected crashes or power failures. To activate Auto Save, select File > Auto Save from the menu. By default, the delay time is set to 1000 milliseconds (1 second), but you can adjust this value in the settings if you prefer a different interval.
- Settings Sync: Settings Sync is a built-in feature that synchronizes your VS Code settings, extensions, and keybindings across different installations using your GitHub account. This ensures a consistent environment when working on multiple machines, making it easy to switch between devices without the need to manually configure settings each time. To enable Settings Sync, sign in to your GitHub account in VS Code, and follow the prompts to configure synchronization preferences.
- Docker: The Docker extension for VS Code simplifies your work with Docker containers by providing assistance in Dockerfile and docker-compose.yml authoring, project packaging and deployment, and even generating the appropriate Docker files for your project. With the Docker extension, you can easily manage your containers, images, and networks, as well as debug your containerized applications directly within the VS Code environment.
These extensions and settings are just a few examples of how Visual Studio Code can be customized and extended to meet your specific development needs.
The Visual Studio Code Marketplace hosts thousands of extensions, covering a wide range of technologies and tools, making it easy to create a tailored development environment that streamlines your workflow and boosts your productivity.
To discover and install new extensions and themes, simply click on the Extensions icon on the Activity Bar. You can search for extensions using keywords, organize the results in various ways, and effortlessly install your desired extensions.
For this guide, install the Python extension by typing “python” in the Extensions item on the Activity Bar and clicking Install.
Visual Studio Code Configuration Files
It’s worth noting that Visual Studio Code offers extensive configuration through user and workspace settings.
User settings apply globally across all Visual Studio Code instances, whereas workspace settings are specific to a particular folder or project workspace.
Workspace settings provide VS Code with immense flexibility, and we’ll reference them throughout this discussion.
Workspace settings are saved as .json files in a folder called .vscode, located within the project workspace.
[INSERT IMAGE]
Customization of Visual Studio Code Extensions
Visual Studio Code is designed to be a highly customizable and extensible development environment that caters to a wide range of developers with varying preferences and backgrounds.
Keymaps, themes, and language packs are three examples of how VS Code makes it easy for developers to adapt the environment to their needs and preferences:
Key Mapping
Keymaps are sets of keyboard shortcuts that correspond to specific actions in the editor. Developers coming from other text editors or IDEs, such as Atom, Sublime Text, Emacs, Vim, PyCharm, or others, may already be familiar with certain keyboard shortcuts unique to those environments.
To make the transition to VS Code easier, keymaps enable these users to continue using the keyboard shortcuts they are accustomed to. VS Code provides keymap extensions that mimic the keyboard shortcuts from other popular editors, allowing users to maintain their existing workflow and feel right at home in the new environment.
Themes
Themes allow you to customize the appearance of the VS Code user interface, catering to individual preferences for light, dark, or more colorful interfaces.
In addition to the built-in themes that come with VS Code, there are countless community-contributed themes available in the Visual Studio Code Marketplace.
Themes can be easily installed and switched, enabling developers to personalize their coding environment to their liking, improve readability, and reduce eye strain.
Language Packs
Language packs deliver a localized experience by providing translations of the VS Code interface into different languages.
This makes the development environment more accessible to non-English speaking developers and can enhance productivity for those who are more comfortable working in their native language. VS Code supports numerous language packs, which are available through the Visual Studio Code Marketplace.
Once a language pack is installed, the display language can be changed in the settings, allowing developers to work in the language they are most comfortable with.
These three features exemplify the level of customization and adaptability that Visual Studio Code offers, ensuring that developers from various backgrounds can create a tailored development environment that suits their specific needs and preferences.
Starting a New Python Program in VS Code
To begin our journey into Python development with Visual Studio Code, let’s start by creating a new Python program.
There are 3 easy to create a new file in VS Code,
- Press Ctrl+N on your keyboard.
- Select File > New from the top menu bar.
- The Visual Studio Code UI features the Command Palette, allowing you to search and execute any command without leaving the keyboard. To access the Command Palette, press Ctrl+Shift+P, then type “
>File: New File
” and hit Enter to open a new file.
Regardless of your chosen method, you should now see a VS Code window resembling the following: Once you’ve opened a new file, you can start writing code.
Writing Python Code
As a test, let’s quickly implement a simple algorithm that calculates the Fibonacci sequence up to a given number. Start typing the following code in the new tab you just opened:
def fibonacci(n):
sequence = [0, 1]
for i in range(2, n):
sequence.append(sequence[-1] + sequence[-2])
return sequence
Your screen should display something similar to this:
[INSERT IMAGE]
You might have noticed that Visual Studio Code provides keyword highlighting, auto-formatting, or any other helpful features.
The reason is that, at the moment, VS Code is unsure of the file type it’s dealing with. The buffer is labeled “Untitled-1“, and if you glance at the lower right corner of the window, you’ll notice the words “Plain Text“.
VS Code is therefore currently seeing this code as plain text, and therefore not using any of the syntax.
To activate the Python extension, you need to save the file which can be done in one of these ways:
- Pressing Ctrl+S on your keyboard
- Selecting File > Save from the menu
>File: Save File
from the Command Palette (Ctrl+Shift+P).
Now enter the name as fibonacci.py.
VS Code will recognize the .py
extension and correctly interpret the file as Python code. Your window should now look like this:
[INSERT IMAGE]
That’s a significant improvement! VS Code now automatically formats the file as Python, which you can confirm by checking the language mode in the lower left corner.
If you have multiple Python installations (such as Python 2.7, Python 3.x, or Anaconda), you can switch the Python interpreter used by VS Code by clicking the language mode indicator or selecting Python > Select Interpreter from the Command Palette.
By default, VS Code supports formatting using pep8, but you can also choose black or yapf if you prefer.
[INSERT IMAGE]
Now let’s complete the Fibonacci code. To experience IntelliSense in action, type the code directly instead of copy-pasting. Your screen should resemble something like this:
[INSERT IMAGE]
Here’s the full code for a basic Fibonacci sequence generator:
def fibonacci(n):
sequence = [0, 1]
for i in range(2, n):
sequence.append(sequence[-1] + sequence[-2])
return sequence
n = 10
fib_seq = fibonacci(n)
print(f"Fibonacci sequence up to {n}: {fib_seq}")
As you type this code, VS Code automatically indents the lines under the for statement correctly, adds closing parentheses, and provides suggestions.
That’s the power of IntelliSense working for you.
Executing Python Code
Running Python code in Visual Studio Code is a seamless process that doesn’t require you to leave the editor. Here’s an expanded explanation of how to run Python code directly within VS Code:
- Write your Python code in the editor, and make sure to save the file (you can use the keyboard shortcut Ctrl+S or Cmd+S on macOS).
- Right-click anywhere in the editor window, and choose “Run Python File in Terminal” from the context menu. Alternatively, you can use the keyboard shortcut Ctrl+Alt+N or Cmd+Alt+N on macOS.
- When you choose “Run Python File in Terminal,” VS Code will open the Terminal pane at the bottom of the window. The Terminal pane is an integrated terminal that runs within the VS Code environment, providing a convenient way to execute commands and scripts.
- In the Terminal pane, you’ll see your Python code being executed. The terminal will display the output of your code, allowing you to observe the results and identify any issues or errors that may have occurred during the execution.
- If your code requires user input, the Terminal pane also enables you to interact with your code directly by entering the required input when prompted.
- Once the code execution is complete, the Terminal pane will return to the command prompt, allowing you to run additional commands or execute your code again if necessary.
This built-in feature of Visual Studio Code makes running Python code a more streamlined and efficient process, allowing you to focus on writing and testing your code without having to switch between multiple windows or tools.
Additionally, the integrated Terminal pane offers a familiar environment for those who regularly work with command-line interfaces, making it a valuable tool for developers at any skill level.
Python Linting Support
Linting is the process of analyzing code to identify potential errors, stylistic issues, or deviations from coding standards. In Visual Studio Code, linting can help you catch issues early on and write cleaner, more consistent code. When you first start using VS Code for Python, you might see a pop-up stating that linting is unavailable. You can quickly install linting support from that pop-up, with PyLint being the default linter.
VS Code supports several Python linters, allowing you to choose the one that best fits your needs and preferences. The current list of supported linters includes:
- pylint: A popular linter that checks code for errors, stylistic issues, and adherence to PEP 8 standards.
- flake8: A linter that combines PyFlakes, pycodestyle (previously pep8), and McCabe complexity analysis. It checks for syntax errors, naming conventions, and complexity.
- mypy: A static type checker that enforces type hints in your code, helping you catch potential type-related issues before runtime.
- pydocstyle: A linter focused on checking adherence to Python docstring conventions, ensuring that your documentation is consistent and follows best practices.
- pep8: A linter (now part of pycodestyle) that checks your code for compliance with PEP 8, the Python style guide.
- prospector: A comprehensive linter that combines several linters and static analysis tools to provide a unified interface for code quality checking.
- pyllama: A code audit tool that wraps around other linters (like pylint, pycodestyle, and pydocstyle) and provides an aggregated report of code issues.
- bandit: A security-oriented linter that scans your Python code for potential security vulnerabilities and issues.
The Python linting page in the VS Code documentation offers comprehensive details on setting up each linter. You can find information about installing the required packages, enabling specific linters, and configuring their settings.
It is important to note that the choice of linter is a project workspace setting, rather than a global user setting.
This means that you can use different linters for different projects, catering to specific project requirements and team preferences. To configure the linter for a specific workspace, you can create or modify the .vscode/settings.json file in the project directory and add the necessary settings for your chosen linter.
TIP: The choice of linter is a project workspace setting, rather than a global user setting.
Editing an Existing Python Project
In the Fibonacci sequence example, you created a single Python file. While that’s great for illustration purposes, often you’ll develop larger projects over an extended period.
A typical new project workflow might resemble the following:
- Create a folder to hold the project (which may include a new GitHub project)
- Change to the new folder
- Create the initial Python code using the command code filename.py
Project-Focused Functionality in Visual Studio Code
Working with a Python project (as opposed to a single Python file) in Visual Studio Code unlocks a wealth of functionality, allowing VS Code to truly excel. Let’s explore how it performs with a more extensive project.
Recreating a Project in Visual Studio Code
To showcase the project-focused features of Visual Studio Code, I’ll start recreating the shunting yard algorithm as an equation evaluation library in Python. To follow along, feel free to clone the repo locally.
After creating the folder locally, you can quickly open the entire folder in VS Code. My preferred method (as mentioned earlier) is modified as follows since I already have the folder and basic files created:
cd /path/to/project
code .
Opening Folders and Environments in Visual Studio Code
VS Code recognizes and utilizes any virtualenv, pipenv, or conda environments it encounters when opened in this manner. There’s no need to activate the virtual environment first! You can even open a folder from the UI by selecting:
- File > Open Folder from the menu,
- pressing Ctrl+K followed by Ctrl+O on the keyboard,
- or choosing
>File:Open Folder
from the Command Palette (Ctrl+Shift+P).
For my equation evaluation library project, this is what I see:
[INSERT IMAGE]
File Management in Visual Studio Code
Upon opening the folder in Visual Studio Code, it also loads the files you last accessed (which is configurable). You can open, edit, run, and debug any file listed.
The Explorer view in the Activity Bar on the left displays all the files in the folder and indicates the number of unsaved files present in the current set of tabs.
Automatic Test Identification in Visual Studio Code
VS Code can automatically identify existing Python tests written using the unittest framework, or the pytest or Nose frameworks if installed in the current environment.
For the equation evaluation library, I have a unit test written using unittest, which you can use as an example.
Running Existing Unit Tests in Visual Studio Code
To execute your existing unit tests, right-click any Python file in the project and select Run Current Unit Test File. You’ll be prompted to specify the test framework, the location in the project to search for tests, and the filename pattern your tests employ.
These preferences are saved as workspace settings in your local .vscode/settings.json file and can be modified there. For this equation project, select unittest, the current folder, and the pattern *_test.py.
Once the test framework is configured and the tests are discovered, you can run all your tests by clicking Run Tests on the Status Bar and choosing an option from the Command Palette:
[INSERT IMAGE]
You can also execute individual tests by opening the test file in VS Code, clicking Run Tests on the Status Bar, and selecting Run Unit Test Method… followed by the specific test you want to run.
This makes it incredibly easy to tackle individual test failures and re-run only the failed tests, saving a significant amount of time! Test results are displayed in the Output pane under Python Test Log.
Debugging Features in Visual Studio Code
VS Code, despite being primarily a code editor, also allows you to debug Python code directly within the application. It offers a range of debugging features, including:
- Tracking variables automatically
- Monitoring expressions
- Setting breakpoints
- Examining the call stack
You can find all these features in the Debug view on the Activity Bar:
[INSERT IMAGE]
Debugging Versatility in Visual Studio Code
When it comes to debugging, VS Code is quite versatile. It can manage Python applications running in the built-in terminal or an external terminal instance.
It can even attach to running Python instances and debug Django and Flask apps.
- For a single Python file, debugging is as easy as starting the debugger with F5.
- You can step over functions with F10,
- Or step into functions with F11,
- and exit the debugger using Shift+F5.
- You can also set breakpoints with F9, or by clicking in the left margin of the editor window.
Debug Configuration Setup in Visual Studio Code
For more complex projects, such as Django or Flask applications, you need to set up a debug configuration first.
Here are the steps to set up a debug configuration:
- Open the Debug view by clicking on the bug icon in the Activity Bar.
- Choose the Configuration drop-down at the top of the Debug view.
- Click on “Add Configuration” and then select “Python” from the list of available options.
[INSERT IMAGE]
This will create a launch.json file in your project’s “.vscode” folder with a template configuration for Python debugging.
You can then customize this file according to your project requirements. Some common options include:
- “name”: A descriptive name for your debug configuration.
- “type”: The type of debugger to use. For Python, this should be set to “python”.
- “request”: The request type, which can be either “launch” (to start the application with the debugger) or “attach” (to connect to an already running application).
- “program”: The entry point of your application. For Django or Flask projects, this should point to the “manage.py” or “app.py” file, respectively.
- “args”: Any command-line arguments that your application requires.
- “env”: Environment variables that need to be set for your application.
Once you’ve set up the debug configuration, you can select it from the Configuration drop-down menu in the Debug view.
This will ensure a smooth debugging experience tailored to your specific app or project.
Advanced Debugging Capabilities in Visual Studio Code
Visual Studio Code offers several advanced debugging capabilities that can further enhance your debugging experience:
- Remote Debugging: With the Remote Development extension pack, you can debug applications running on remote machines or containers, such as in cloud-based or containerized environments. This extension pack includes Remote – SSH, Remote – Containers, and Remote – WSL. After closing the launch.json file in the editor, choose the appropriate configuration for your application from the Configuration drop-down menu.
- Debugging Templates: For web frameworks like Django or Jinja templates, you can install the appropriate extensions (such as the Python extension for Django or the Jinja extension for Jinja templates) to step through your templates and view variable values during the debugging process.
- Conditional Breakpoints: VS Code supports setting breakpoints that pause the execution only when a specified condition is met. This feature helps you isolate issues that occur under specific circumstances, enabling more efficient debugging.
- Logpoints: Logpoints allow you to add logging statements to your code without modifying the source. These logpoints work like console.log() statements but are executed only when a particular condition is met. This feature is useful for temporary logging during debugging without cluttering your code.
- Multi-Target Debugging: You can debug multiple processes simultaneously in VS Code, such as a client and server application. This capability helps you understand the interactions between different components of your system.
- Debugging Extensions: The VS Code ecosystem includes numerous extensions that can provide language-specific debugging capabilities, visualizations, performance profiling, and more, further enriching your debugging experience.
In summary, the advanced debugging capabilities in Visual Studio Code, coupled with the basic features, allow developers to efficiently identify and resolve issues in their code across various applications, platforms, and environments.
Git Integration
You can install support for other source control management systems (SCMs) in VS Code, allowing you to use them concurrently.
To access source control, navigate to the Source Control view in the Activity Bar on the left side of the VS Code window.
[INSERT IMAGE]
The Git integration in VS Code makes it simple to work with version control and collaborate with others on your projects. Additionally, you can take advantage of various extensions to further enhance your experience, such as GitLens, which provides advanced Git features directly in your editor.
[INSERT IMAGE]
Git Management Tasks in Visual Studio Code
Visual Studio Code provides seamless Git and GitHub integration when it detects a .git folder in your project directory.
Here are some of the tasks you can perform with Git in VS Code:
- Initialize a Git repository: If your project doesn’t have a .git folder, you can initialize a new Git repository using the Command Palette or the Source Control view.
- Clone a repository: You can clone an existing remote repository using the Command Palette or by selecting the “Clone Repository” option in the Source Control view.
- View changes: See the changes made to your files and compare the differences between the current version and the previous one.
- Stage and unstage changes: Use the Source Control view to stage or unstage changes made to your files.
- Commit changes: Write a commit message and commit your staged changes to your local repository directly in the Source Control view.
- Push and pull changes: Sync your local repository with the remote repository by pushing your commits and pulling new changes.
- Branch management: Create, switch, merge, and delete branches using the Source Control view or the Command Palette.
- View commit history: You can view the commit history for your repository using the Command Palette or with the help of extensions like GitLens.
- Resolve merge conflicts: In case of conflicts, you can resolve them directly in the editor using the built-in merge conflict resolution tools.
- Stashing changes: Temporarily save your uncommitted changes with Git stash, and apply them later when you need them.
- Interactive rebase: Rewrite your commit history by squashing, editing, or reordering commits.
- Access Git commands: Execute Git commands using the Command Palette or the integrated terminal.
- Git blame: View the author, commit hash, and commit date for each line of code in your files with the help of extensions like GitLens.
These are just a few of the many tasks you can perform with Git integration in Visual Studio Code. To access most of these tasks, you can use the Command Palette or the corresponding UI elements in the Source Control view.
This can all be viewed directly in the VS Code UI
[INSERT IMAGE]
Visual Studio Code does recognize changes made outside the editor and behaves appropriately. When you switch back to VS Code after making changes in another program or editor, it will automatically refresh the files and display the updated content.
Additionally, the Source Control view will update to reflect the new changes.
Committing and Pushing Changes with Git in Visual Studio Code
Committing changes in VS Code is easy and efficient. When you modify or create new files, they will be marked with an “M” (modified) or “U” (untracked) in the Source Control view.
To stage these changes, hover over the file and click the plus sign (+) that appears.
Once you’ve staged your changes, enter a commit message in the input field at the top of the Source Control view, and click the checkmark icon to commit your changes.
Finally, you can push your local commits to your remote repository (e.g., GitHub) from within VS Code.
To do this, you can either click the “Sync” button in the Source Control view menu or use the “Synchronize Changes” option in the status bar next to the branch indicator.
This will push your local commits and pull any new changes from the remote repository, ensuring that your local and remote repositories stay in sync.
[INSERT IMAGE]
Conclusion
That brings us to the end of this tutorial about Getting Started with Python Development in Visual Studio Code.
I hope you enjoyed learning about Visual Studio Code and how it can be used for Python development.
To summarize, in this article, we covered:
- Installing Visual Studio Code on various platforms, making it a versatile and accessible option for developers.
- Finding and installing extensions that enhance the Python development experience in VS Code, such as language support, linting, testing, and debugging.
- The features VS Code offers, like IntelliSense and auto-formatting that make writing Python code more efficient and enjoyable.
- Running and debugging Python programs directly within the VS Code environment, allowing for a seamless development experience.
- Working with Git and GitHub repositories from within VS Code, enabling easy version control and collaboration on projects.
Visual Studio Code has indeed become a popular choice for many developers, including those working with Python. Its extensive features, customization options, and integration with various tools make it a powerful and versatile editor. We hope you continue to explore and enjoy using Visual Studio Code for your Python development and beyond.