June 8, 2025

Create local package and using it - [1]

Introduction

In this post, I will have a look at how to create a local Python package and use it.

Purpose

In usual cases, we use Python packages from PyPi, with a pip install command that is widely used or we are familiar with.

What I would like to achieve here is to not upload on PyPi and only use pip install as a local package.

I decided to learn about it as I realised that my company deals with local packages, and I felt like I need to know the structure of it.

This post references Create and Access a Python Package from GeeksforGeeks.

Steps

The main 3 steps are as follow:

  1. Create directory: this is the same as the package name.

  2. Put classes and required functions in this directory.

  3. Create an __init__.py file inside the directory, to let Python know that the directory is a package.*

Note: __init__.py file can be placed after creating the directory

1. Create directory

2. Classes and functions in package

1
2
3
4
5
6
7
8
class Kiel:
def __init__(self):
self.towns = ['Laboe', 'Kronshagen', 'Suchsdorf']

def printTowns(self):
print('These are the towns in Kiel:')
for town in self.towns:
print('\t%s ' % town)
1
2
3
4
5
6
# Import classes from your brand new package
from Kiel import Kiel

# Create an object of Kiel class & call its method
ModTowns = Kiel()
ModTowns.printTowns()

3. __init__.py file in the directory

At the end, you’ll be able to see something like this (please ignore the outputs before):

3 towns in Kiel

There were errors initially with naming, such as from Kiel import Towns.

I also realised that I didn’t add the __init__.py and it works fine.

Although this is correct, the reason why it’s not adopted is because you wouldn’t be able to differentiate directories that are for packages and normal Python scripts - more information can be found here.

About this Post

This post is written by Winterdusk, licensed under CC BY-NC 4.0.

#python, package, class, function, constructor, object