Introduction to Python Programming: Creating a Python Project Boilerplate

2020-07-22 16:34:20 | #programming #python

Tested On

  • Linux Ubuntu 20.04
  • Windows 10
  • macOS Catalina

What is Python, why is it worth learning, and how does it compare to other programming languages?

Python is a general-purpose programming language, which means it can be used to code a variety of applications, including backend (server-side), mobile, desktop, data analysis, and standalone system scripts. Today, we're going to learn the steps you need to carry out at the beginning of every Python project.

How to Install Python on Windows 10

Download and install the latest Python 3 package, and make sure to select the checkbox for "Add Python 3.x to PATH" during this process. We'll be using Python 3.8 in this tutorial. After the installation is complete, open or relaunch PowerShell, and type/run python --version and make sure you see Python 3.8.x.

Now install VirtualEnv by running pip install virtualenv

How to Install Python on Linux Ubuntu

First, check to see if Python 3 is already installed by running python --version in the command line. If the version is 3.7 or higher, you can skip the installation steps. Otherwise, run:

sudo apt update
sudo apt install software-properties-common
sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt update
sudo apt install python3.8

Make sure you have python and pip for version 3.8+ by running python --version and pip --version

Now install VirtualEnv by running pip install virtualenv

How to Install Python 3 on macOS

brew install pyenv
pyenv install 3.8.2
pyenv global 3.8.2
echo -e 'if command -v pyenv 1>/dev/null 2>&1; then\n  eval "$(pyenv init -)"\nfi' >> ~/.bash_profile

Make sure you have python and pip for version 3.8+ by running python -V and pip -V

Now install VirtualEnv by running pip install virtualenv

How to Set Up a Python Project Boilerplate

Boilerplate is just a shorter way of saying "a set of standards, routines, or methods." Boilerplates make it easier to understand our project files and folders when we come back to them in the future. They also make it easier for team members, who are familiar with the standard, to identify where everything is.

One of the most crucial first steps is to set up a virtual environment for our project. This lets us keep all of the module dependencies and their versions isolated within the project, so that each project can have its own dependencies without causing conflicts.

How to Create a Python Project with Windows 10 PowerShell 2.0+

cd ~
New-Item -ItemType "directory" -Path ".\python-boilerplate"
cd python-boilerplate
New-Item -ItemType "file" -Path . -Name "main.py"
New-Item -ItemType "file" -Path . -Name "README.md"
New-Item -ItemType "file" -Path . -Name "requirements.txt"
New-Item -ItemType "file" -Path . -Name "setup.py"
New-Item -ItemType "file" -Path . -Name ".gitignore"
virtualenv venv
.\venv\Scripts\activate

You may get the following error while running the .\venv\Scripts\activate command:

Error
.\venv\Scripts\activate : File C:\Users\username\python-boilerplate\venv\Scripts\activate.ps1
cannot be loaded because running scripts is disabled on this system. For more information,
see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170.
At line:1 char:1
+ .\venv\Scripts\activate
+ ~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : SecurityError: (:) [], PSSecurityException
    + FullyQualifiedErrorId : UnauthorizedAccess

To resolve this, close PowerShell, and relaunch it with the "Run as Administrator" option. You may have to search for PowerShell in the toolbar, click the > button and then click the "Run as Administrator" button from the list.

Then run the following:

Set-ExecutionPolicy RemoteSigned
cd ~
.\venv\Scripts\activate

To verify that the virtual environment is active, make sure (venv) is in the PowerShell command prompt. For example, (venv) PS C:\Users\username\python-boilerplate>

How to Create a Python Project with Linux Ubuntu 14.04+ or macOS

cd ~
mkdir python-boilerplate
cd python-boilerplate
virtualenv -p python3 venv
source venv/bin/activate
touch main.py
touch README.md
touch requirements.txt
touch setup.py
touch .gitignore

To verify that the virtual environment is active, make sure (venv) is in the terminal command prompt.

After running the above commands, make sure your skeleton looks like the following example and that the virtual environment is active.

▾ python-boilerplate/
  ▸ venv/
  main.py
  README.md
  requirements.txt
  setup.py
  .gitignore

Example README.md File

Copy the following to your README.md file. Use this file to document installation and execution steps so that you don't need to remember how to run your program in the future.

Filename: README.md

# python-boilerplate

```
# Creating the virtual environment
virtualenv venv

# Activating virtualenv on Linux Ubuntu /macOS
source venv/bin/active

# Activate virtualenv on Windows 10
.\venv\Scripts\activate

# Installing Python dependencies
pip install -r requirements.txt

# How to run
python main.py

# Deactivating the virtual environment
deactivate
```

The README.md should be simple from the outset. Indicate the project name, installation and execution steps. In our example, we instruct the developer to install all the dependencies into the virtual environment. While the virtual environment is activated, you can run python main.py as often as you like.

If you forget to activate the virtual environment, you will oftentimes receive a ModuleNotFoundError similar to the following. This just means you need to run source venv/bin/activate or .\venv\Scripts\activate from the root folder, then pip install MODULENAME for each dependency it's asking you to import, and then python main.py in order to run the program.

Traceback (most recent call last):
    File "test_project.py", line 2, in 
      import pytest
  ModuleNotFoundError: No module named 'pytest'

Example .gitignore File

Add the following to your .gitignore file.

venv

This line simply tells git not to commit the venv folder to the repository. We won't need to commit venv because the list of dependencies are indicated in the requirements.txt file.

How to Generate the requirements.txt File

After running source venv/bin/activate or .\venv\Scripts\activate you will notice that the venv folder contains various modules. We're going to create a list of all of those modules/dependencies with the following command:

pip freeze > requirements.txt

You should now have a list of those modules and their versions. This keeps track of dependencies and allows us to easily install them again in the future.

Example Python setup.py File

Copy the following to your setup.py file and update with your own details.

Filename: setup.py

try:
  from setuptools import setup
except ImportError:
  from distutils.core import setup

config = {
  'description': 'Project description',
  'author': 'Name',
  'url': 'Home page of the application',
  'download_url': 'Download link',
  'author_email': 'user@email.com',
  'version': '0.1.0',
  'install_requires': ['pytest'], #dependencies
  'packages': ['NAME'],
  'scripts': [],
  'name': 'projectname'
}

setup(**config)

The setup.py file contains metadata for our project. This is required if you're going to make your project pip intallable. If you don't know what that means or you just want to make this project private, you can skip this file.

Full main.py Code

Copy the following to your main.py file.

Filename: main.py

if __name__ == '__main__':
    print('Hello world!')

For the time being, we'll just be printing "Hello world!" to the terminal. Line 1 tells the program what to execute when it is invoked directly, and not imported, by checking to see if "name" is set to the script/module.

How to Run a Python Program

Run the following command:

python main.py

If everything was set up properly, you should see Hello world! printed to the console. Feel free to experiment with this file by printing various things to the console.

How to Code Your First Python Function

Functions (or methods) allow us to define reusable logic that we can invoke with different parameters. We define functions with the def keyword. The format is:

def function_name(parameter1, parameter2...):
    # do something

Let's use this example to update your main.py file with the following code:

def add(a, b):
    return a + b

if __name__ == '__main__':
    sum = add(1, 2)
    print(sum)
    print(add(2,2))

Here, we define an add function that accepts the variables a and b, adds them together, and returns the sum. In line 5, we call add,pass in 1 and 2, and return 3, which we can store in the variable sum and print to the console.

Line 7: shows us that we don't need to store the returned value of add into the variable sum. We can immediately pass the returned value into print directly.

Run python main.py again to see the calculations printed to the console. That concludes our tutorial about setting up a basic Python 3 project. Deactivate your virtual environment by running deactivate from the root directory, and confirm that (venv) is no longer in the command prompt.

Comments

You must log in to comment. Don't have an account? Sign up for free.

Subscribe to Our Newsletter

Would you like to receive free whitepapers and other IT news? Just leave your email address below. You may opt out at any time.



Tell Us About Your Project









Contact Us

Do you have a specific IT problem that needs solving or just have a general IT question? Use the contact form to get in touch with us and an IT professional will be with you, momentarily.

Hire Us

We offer web development, enterprise software development, QA & testing, google analytics, domains and hosting, databases, security, IT consulting, and other IT-related services.

Free IT Tutorials

Head over to our tutorials section to learn all about working with various IT solutions.

Contact