How to start a Python project in 2024

When I begin a new Python project, one of the first steps I take is to create a virtual environment. This is crucial for managing dependencies and ensuring that the libraries used in my project do not conflict with those of other projects or the system itself. Here’s how I set up a Python project using a virtual environment.

Step 1: Create a New Project Directory

I start by creating a new directory for my project and navigate into it:

mkdir my_project
cd my_project

Step 2: Initialize a Git Repository

Next, I initialize a git repository to manage version control:

git init

Step 3: Create the Virtual Environment

I use the venv module to create a virtual environment in my project directory, naming it after my project followed by -venv to maintain clarity:

python -m venv myproject-venv

This command creates a directory named myproject-venv where the virtual environment files are stored.

Step 4: Activate the Virtual Environment

Before installing any packages, I activate the virtual environment. The method differs slightly depending on the operating system:

  • On macOS and Linux:

      source myproject-venv/bin/activate
    
  • On Windows:

      .\myproject-venv\Scripts\activate
    

The prompt in the shell changes to show the name of the environment, indicating that it is now active.

Step 5: Install Required Packages

With the virtual environment activated, I install the necessary packages using pip:

pip install <package_name>

For instance, to install Flask:

pip install flask

Step 6: Save Dependencies

It’s good practice to keep track of the project's dependencies. I do this by creating a requirements.txt file:

pip freeze > requirements.txt

This file is crucial for replicating the environment on other machines or by other developers working on the project.

Step 7: Start Coding

Now, I can start coding my project. I create Python scripts in the project directory and run them using the Python interpreter that is part of my virtual environment.

Step 8: Deactivate the Virtual Environment

When I'm done working, I deactivate the virtual environment by running:

deactivate

This workflow helps me maintain a clean and organized working environment and makes it easier to manage project-specific dependencies. By following these steps, I ensure that each of my Python projects is set up correctly and ready for development.