Effortless Python Dependency Management: Switching to Poetry Instead of Pip

Effortless Python Dependency Management: Switching to Poetry Instead of Pip

Setting up a virtual environment is crucial for maintaining clean, isolated Python environments, especially when working on machine learning projects in VSCode. While many developers traditionally use pip for managing dependencies, Poetry offers a more streamlined and user-friendly alternative.

I will walk through the steps of setting up a Python virtual environment in VSCode using Poetry.

Prerequisite:

Before starting, ensure you have Anaconda or Miniconda installed to manage Python installations if needed. You’ll also need to install Poetry globally on your system. You can install Poetry by running:

curl -sSL https://install.python-poetry.org | python3 -

Steps to Create a Virtual Environment in VSCode:

  1. Navigate to Your Project Folder: Open your terminal and navigate to the folder where
    you want to practice or already have your project files. Use the following command to open the folder in VSCode:

code .

  1. Initialize a Poetry Project: To create a virtual environment using Poetry, you need to
    initialize a project inside the folder.
    This will create a pyproject.toml file, which is the main configuration file for your project dependencies.

poetry init

Follow the prompts to configure your project (you can skip some optional fields by pressing Enter).

  1. Install Python Version: To create a virtual environment with a specific Python version
    (for example, Python 3.12), you can specify the Python version using Poetry. First, make sure Python 3.12 is installed on your system:

poetry env use python3.12

This creates a virtual environment with the specified Python version.

  1. Activate the Virtual Environment: Poetry automatically manages the activation of the
    virtual environment, but you can manually activate it by running:

poetry shell

  1. Add Required Python Packages: Instead of using requirements.txt,
    Poetry manages dependencies in the pyproject.toml file.
    To add the required libraries for your ML project, run:

poetry add numpy pandas sklearn ipykernel

This will add these libraries to the project and lock the versions in the poetry.lock file for consistency.

  1. Set Up Jupyter Notebooks in VSCode: To use Jupyter notebooks within VSCode, you need to install
    the ipykernel package in your environment. You already added it with the previous command,
    but to ensure that Poetry recognizes it for Jupyter notebook usage, run:

poetry run python -m ipykernel install --user

Once this is set up, you can open .ipynb files in VSCode and start using Jupyter notebooks within your Python environment.

  1. Open Jupyter Notebooks in VSCode: After installing the necessary packages and setting up
    the environment, simply open any .ipynb file in VSCode.
    VSCode will detect your Poetry-managed virtual environment.

vamsi manyam Avatar