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:
Create directory: this is the same as the package name.
Put classes and required functions in this directory.
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
We are creating
Cities
directory for instance here.Here I will add, let’s say the 3 cities in Schleswig-Holstein:
Kiel
,Flensburg
,Husum
. These cities will be the modules.
2. Classes and functions in package
- Each city can be created as files with .py endings (i.e.
Kiel.py
), creating contents with classes, using constructor.
1 | class Kiel: |
- Let’s try with this with the capital city
Kiel
, in a separate script in the same directory, calledschleswig-holstein.py
.
1 | # Import classes from your brand new package |
3. __init__.py
file in the directory
- Self-explanatory. Let’s place this file in the directory, and run the code.
At the end, you’ll be able to see something like this (please ignore the outputs before):
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.