Creating Python Development Environment on Linux


Python is undoubtedly among the most utilized programming languages in software development. I have used the language to write short scripts that scrape data and analyze geospatial data, design user interfaces for desktops, create web applications' backends, and others. When I started writing Python code, I had only had theoretical knowledge of how to set up an environment for writing Python-based software which I improved over the years through practical experience in projects, some of which can be referred to from my GitHub profile. Many beginners find it hard to get started with writing for multi-functional software, one which does a number of tasks such as:

  • Desktop user interface app that loads an image from the file system
  • Blog web application that facilitates publishing of blog posts and registering new users

This article's objective is to complement the concepts that I have highlighted in Python Fundamentals and Python Virtual Environments articles and demonstrate some steps that you can apply ahead of writing your software using Python. Setting up a Python development environment is essential for a variety of reasons, all of which contribute to making your coding experience more efficient, organized, and productive. Here are some key reasons for setting up a proper Python development environment:

  1. Clean Code Separation: Within your development environment, you can segment code into distinct projects or modules making it simpler to organize, comprehend, and collaborate on your codebase. Maintainability and good coding practices are supported by clear separation which can be implemented by setting up a development environment.
  2. Consistent Coding Style: The majority of Python projects follow a particular coding style that is frequently specified by programs like PEP 8 (Python Enhancement Proposal 8). Consistency and readability are guaranteed by configuring your development environment to automatically format your code in accordance with these guidelines.
  3. Efficient Collaboration: The use of the same tools and libraries by all team members is ensured by a consistent development environment which facilitates communication and lessens the possibility of compatibility problems in the future of the project.
  4. Customization: You can tailor your development environment to your preferences by choosing your favorite code editor or integrated development environment (IDE), and setting up keybindings, themes, and extensions that enhance your development workflow.
  5. Isolation and Dependency Management: Isolating project-specific dependencies is made easier by using virtual environments. By doing this, conflicts between projects that might need various versions of the same library are avoided. Additionally, this isolation makes it simpler to control and recreate the environment on many systems.

With the key reasons for setting up the Python development environment listed above, let's now dive into the actual steps. Please note that I am doing this on Ubuntu, one of the flavors of the Linux distribution.

Installing Python

We definitely require Python software to write Python code and this shall be the first requirement that I consider. Ubuntu comes shipped with Python, in which case you can check by writing in your terminal.

python3 --version

which should output the version of Python installed as shown below.

Python 3.10.12

You can also check with which command that appears as shown below

$which python3
/usr/bin/python3

Or the alternative whereis command which should output the locations of Python as shown below

$whereis python3
python3: /usr/bin/python3 /usr/lib/python3 /etc/python3 /usr/share/python3 /usr/share/man/man1/python3.1.gz

If for some reason your Linux distro does not have Python, please ensure that you have updated it. Then install Python using the steps in these links:

Setting Up Integrated Development Environment

An IDE is a piece of software that offers an extensive collection of features and tools to help programmers write, test, and debug code. By merging many tools into a single interface, IDEs are made to streamline the development workflow, making it easier for programmers to work on their projects. To develop Python applications, you will, at the very least need a code/text editor however, an IDE provides more functionality that improves the development experience.

Any modern IDE has the following:

  1. Code Editor: Supports syntax highlighting, code completion, and formatting. These features help developers write code more quickly and with fewer errors.
  2. Debugger: This allows developers to set breakpoints, step through code, inspect variables, and diagnose issues in their programs.
  3. Compiler: Depending on the programming language, an IDE can integrate with compilers or interpreters to compile or run code directly from the interface.
  4. Version Control Integration: Many IDEs support version control systems like Git, enabling developers to manage and track changes to their code directly within the IDE.
  5. Integrated Terminal: Some IDEs offer an integrated terminal, allowing developers to run command-line commands without leaving the IDE.
  6. Refactoring Tools: Refactoring tools in IDEs assist developers in restructuring and improving their code while maintaining functionality.
  7. Documentation Tools: IDEs might include features to generate and display documentation from code comments and docstrings.

I would recommend using the following IDEs for Python development:

  • PyCharm - A feature-rich IDE specifically designed for Python development.
  • Visual Studio Code - A lightweight and highly customizable code editor with strong support for Python through extensions.
  • Spyder - An IDE tailored for scientific and data science programming in Python.
  • Jupyter Notebook - An interactive environment commonly used for data analysis and scientific computing.

However, you are at liberty to use any other that you prefer. You can refer to the respective documentation for installing either of the IDEs listed above. By offering an all-in-one solution for authoring, testing, debugging, and managing code, IDEs generally streamline and improve the development process. Depending on their tastes, the programming language they're using, and the features that best suit their workflow, developers can select an IDE.

Setting Up Version Control

This is optional but a recommended step. You will use a version control system like Git if you wish to monitor changes to your code or if you intend to work on projects with others. You can establish a Git repository for your project and manage your codebase using tools from GitHub or GitLab. To set up either of these, please refer to the following:

Creating Virtual Environment

You will typically use packages and modules that are not part of the standard Python library when writing Python apps. It's possible that some of your Python programs need a different version of the same module. However, a module can only be deployed system-wide in a particular version. A module upgrade for one application could break other apps that depend on an earlier version of that module.

You can utilize Python virtual environments to solve this problem. It is possible to install Python modules locally rather than globally using virtual environments. Each virtual environment has a unique Python binary, and each one's site folders can have a unique independent set of installed Python packages.

Since version 3.3, Python comes with the venv library, which provides support for creating lightweight virtual environments. By using the Python venv module to create isolated Python environments, you can use different package versions for different projects. Another advantage of using venv is that you won’t need any administration privileges to install Python packages.

These articles will guide you on how to create virtual environments, the most straightforward approach is using Python's venv module:

Setting Up Your Project

With the necessary software installed and configured, it is time for you to spin up a Python project. In this step, I will make use of the terminal whose approach is different from that of using the IDE. The steps are as follows:

Creating working directory

In your terminal, navigate to your preferred location. I am using the pwd command to print out the current directory.

$cd /home/someuser/
$pwd
/home/someuser

Create a working directory.

$mkdir working_dir
$cd working_dir/
$pwd
/home/someuser/working_dir

Now that we have a working directory, let's proceed to the next step.

Creating virtual environment

To initialize a virtual environment using the steps highlighted in the links that are in the previous section. For simplicity, we shall stick to using Python's built-in venv. This step assumes that you have already installed a supported version of Python and Pip. If not, please refer to the links in the section for creating a virtual environment. Let's type the following in the terminal.

python3 -m venv .venv

You can confirm  the directory exists by typing the following which shows existing files (if any) and folders:

$ls -a
.  ..  .venv

Which creates a virtual environment folder that may appear hidden due to the dot preceding the name. It has been a standard to use venv as the name of the virtual environment however, you may name yours as you prefer.

To activate the virtual environment, you can either use a dot or the source command. Let's activate the virtual environment.

. venv/bin/activate

OR

source venv/bin/activate

You will notice the name of the virtual environment in the shell prompt, which is (.venv) $.

Initializing version control using Git

Assuming that you have installed Git, it is now time to initialize a Git repository, navigate into your project directory and type the following:

$git init
Initialized empty Git repository in /home/someuser/working_dir/.git/

Create a python-specific .gitignore file containing a list of files and folders to ignore when pushing to the remote repository such as GitHub or Bitbucket. Please refer to Toptal's .gitignore generator for this and search for Python which will generate a gitignore specific to the Python project.

 

Toptal's Gitignore Generator

Alternatively, you can navigate to this link which is the same output as the above. Copy and paste the content in a file named .gitignore which shall instruct Git to ignore whatever is listed. At this point, we have set up the necessary configuration for Git to get started with project creation. For your reference, the generated .gitignore template appears in the browser (in part) as shown below.

Gitignore file (in part)

Lets check the folders present in the working directory. You should be having git and virtual environment folders as shown below.

$ls -a
.  ..  .git  .venv

Setting Up Python Project

We shall be creating a Django application. The first step shall be installing the necessary package which shall be Django, followed by creating a Django project and app. To get started, ensure that the Python virtual environment is active and that you are in the working directory. Let's install Django.

(.venv) $pip install Django
Collecting Django
  Using cached Django-4.2.4-py3-none-any.whl (8.0 MB)
Collecting asgiref<4,>=3.6.0
  Using cached asgiref-3.7.2-py3-none-any.whl (24 kB)
Collecting sqlparse>=0.3.1
  Using cached sqlparse-0.4.4-py3-none-any.whl (41 kB)
Collecting typing-extensions>=4
  Using cached typing_extensions-4.7.1-py3-none-any.whl (33 kB)
Installing collected packages: typing-extensions, sqlparse, asgiref, Django
Successfully installed Django-4.2.4 asgiref-3.7.2 sqlparse-0.4.4 typing-extensions-4.7.1(.venv) $pip install Django
Collecting Django
  Using cached Django-4.2.4-py3-none-any.whl (8.0 MB)
Collecting asgiref<4,>=3.6.0
  Using cached asgiref-3.7.2-py3-none-any.whl (24 kB)
Collecting sqlparse>=0.3.1
  Using cached sqlparse-0.4.4-py3-none-any.whl (41 kB)
Collecting typing-extensions>=4
  Using cached typing_extensions-4.7.1-py3-none-any.whl (33 kB)
Installing collected packages: typing-extensions, sqlparse, asgiref, Django
Successfully installed Django-4.2.4 asgiref-3.7.2 sqlparse-0.4.4 typing-extensions-4.7.1

To check installed packages, use pip list

(.venv) $pip list
Package           Version
----------------- -------
asgiref           3.7.2
Django            4.2.4
pip               22.0.2
setuptools        59.6.0
sqlparse          0.4.4
typing_extensions 4.7.1

Also, to check more details about the installed Django package, use pip show Django

(.venv) $pip show Django
Name: Django
Version: 4.2.4
Summary: A high-level Python web framework that encourages rapid development and clean, pragmatic design.
Home-page: https://www.djangoproject.com/
Author: Django Software Foundation
Author-email: foundation@djangoproject.com
License: BSD-3-Clause
Location: /home/someuser/working_dir/.venv/lib/python3.10/site-packages
Requires: asgiref, sqlparse
Required-by: 

We have successfully installed Django. Let's configure the Django project and simple app.

(.venv) $django-admin startproject my_project .
(.venv) $ls -a
.  ..  manage.py  my_project  .venv

You will notice that we have the project folder and management script which didn't exist previously. Now, let's create a simple app that returns an HTTP response.

(.venv) $python manage.py startapp my_app
(.venv) $ls -a
.  ..  manage.py  my_app  my_project  .venv

There is an additional app folder that has been created. Now, let's edit the views.py file for the app using your preferred IDE or text editor. The edited file should appear as shown below.

from django.http import HttpResponse

def http_response(request):
    return HttpResponse('<h1>Hello Python!</h1>')

Let us create a urls.py file inside the my_app folder and add the following code.

from .views import http_response

urlpatterns = [
        path('', http_response, name="http_response"),
        ]

Checking the contents of my_app folder, they'll appear as shown below.

(.venv) $ls -a my_app/
.  ..  admin.py  apps.py  __init__.py  migrations  models.py  tests.py  urls.py  views.py

Finally, let us edit the urls.py file present in the Django project folder i.e. my_project/urls.py file. It should have the following code.

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path("admin/", admin.site.urls),
    path("", include("my_app.urls")),
]

At this point, we have successfully configured our Django project, and it is time to test if our code is working by starting the Django development server. The following information should appear in the terminal. In the event that you get a different message indicating errors, please review the previous steps.

(.venv) $python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).

You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
August 2, 2023 - 15:48:51
Django version 4.2.4, using settings 'my_project.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

If you open your browser and navigate to http://127.0.0.1:8000/ you should see a page with the title as shown below.

Web Page

We have successfully configured a simple Django project and tested it. You can stop the development server by Ctrl+C keys on your keyboard and deactivate the active virtual environment using deactivate command. The final step shall be adding the project under Version Control. This shall be our final step.

$git status
On branch main

No commits yet

Untracked files:
  (use "git add <file>..." to include in what will be committed)
    .gitignore
    manage.py
    my_app/
    my_project/

nothing added to commit but untracked files present (use "git add" to track)

The above output indicates that there are files that are untracked and we need to add them to git.

$git add .
$git commit -m "Initial commit"
[main (root-commit) 94ce99c] Initial commit
 15 files changed, 385 insertions(+)
 create mode 100644 .gitignore
 create mode 100755 manage.py
 create mode 100644 my_app/__init__.py
 create mode 100644 my_app/admin.py
 create mode 100644 my_app/apps.py
 create mode 100644 my_app/migrations/__init__.py
 create mode 100644 my_app/models.py
 create mode 100644 my_app/tests.py
 create mode 100644 my_app/urls.py
 create mode 100644 my_app/views.py
 create mode 100644 my_project/__init__.py
 create mode 100644 my_project/asgi.py
 create mode 100644 my_project/settings.py
 create mode 100644 my_project/urls.py
 create mode 100644 my_project/wsgi.py

Now we have set our project under version control. You can read further on pushing your project to a remote repository from the Git documentation.

Conclusion


We have been able to configure the development environment for Python, minus the practical IDE guide, however, the links to some IDEs have been shared. In summary, setting up a Python development environment provides the foundation for organized, efficient, and productive coding. It ensures proper dependency management, code separation, version control, and tools that enhance your development process and lead to better code quality. You have to keep on practicing to understand the fundamental concepts highlighted in this article. Feel free to reach out for questions related to the subject of this article. Happy hacking!

Related articles

Comments

There are no comments yet.

Captcha* captcha
ABOUT ME
JosephKariuki

Hi, thanks for visiting! My name is Joseph Kariuki, a software developer and this is my website. I am consistently seeking solutions to various problems using coding. This site does not contain ads, trackers, affiliates, and sponsored posts.

DETAILS

Published: Aug. 2, 2023

TAGS
fundamentals python
CATEGORIES
Fundamentals Python