DEV Community

Ege Sabanci
Ege Sabanci

Posted on

Python Packaging System

Overview

This blogpost about, very fundamental solution / example for Python's headache (pain in the ...) relative imports and packaging system.

Repository

You can reach the repository from this link

Steps

  • Create a virtual environment for preventing the dependency confliction of the other projects and the easy management for dependencies of the project that you working on:
>>> python3 -m venv env
Enter fullscreen mode Exit fullscreen mode

We have created the virtual environment for our project. Now, we need to activate it:

>>> source env/bin/activate
Enter fullscreen mode Exit fullscreen mode
  • Creating the setup file:
from setuptools import setup, find_packages

setup(
  name = "python-imports",
  version = "0.0.1",
  packages = find_packages()
)
Enter fullscreen mode Exit fullscreen mode

This find_packages function will lookup to the root and find all packages. Then, we can use these packages (which we have create) in our project like an external package from PYPI.

Q: OK, but how can I create my own package?

A: In simple terms, if you create the __init__.py file in one of folders, Python will behave these folders as packages, even if the __init__.py file is empty!

  • Now, we will install our package locally in editable mode with pip:
>>> pip install -e .
Enter fullscreen mode Exit fullscreen mode
  • Final folder structure:
├── main.py
├── package1/
│   ├── hello.py
│   └── __init__.py
├── package2/
│   ├── hello.py
│   └── __init__.py
├── env/
└── setup.py
Enter fullscreen mode Exit fullscreen mode
  • So, we are good to go! We can import our packages like this (in our example - check the package1 and package2 folders):
# package2/hello.py
from package1.hello import hello_with_name


def hello_from_package2():
  print("Hello from package-2!")


def hello_with_name_package1():
  hello_with_name(name = "Python")
Enter fullscreen mode Exit fullscreen mode

Top comments (0)