Package structure in Python

Introduction

PEP 420

Before studying this article, make sure you are familiar with the topics «sys.path in Python» «Packages in Python» «Namespace packages in Python»

project_name ├── docs ├── README.rst ├── setup.py ├── src │ └── package_name │ ├── __init__.py │ ├── more_source.py │ └── subpackage1 │ └── __init__.py └── tests └── test_code.py

The project root - project_name is not part of the package

.rst stands for reStructuredText

============ Project Name =========== A brief description of the project Section 1 ========= Installation or "quick start" information can go here. Subsetion --------- Some details can go here.

src contains the package code

It is important to remember that if you run Python from project_name, this directory will be added to sys.path

This means everything inside it can be imported. Including what does not lie in package_name

But it is exactly what is in package_name that the user of your software will ultimately get.

It is advisable to keep tests separate from the package

Example

python ├── demo_reader │ ├── README.rst │ ├── setup.py │ ├── src │ │ └── demo_reader │ │ ├── compressed │ │ │ ├── bzipped.py │ │ │ ├── gzipped.py │ │ │ └── __init__.py │ │ ├── __main__.py │ │ ├── multireader.py │ │ └── util │ │ ├── __init__.py │ │ └── writer.py │ └── tests │ └── test_multireader.py ├── test.bz2 └── test.gz

From the src directory you can run

python -m demo_reader ../../test.gz

data compressed with gz by Andrei

# tests/test_multireader.py import unittest import demo_reader.multireader class TestMultireader(unittest.TestCase): def test_initialization(self): demo_reader.multireader.MultiReader('test_file.txt')

Let us look at a package with setuptools

import setuptools setuptools.setup( name="demo_reader", version="1.0.0", description="Tools for reading various file formats", packages=setuptools.find_packages('src'), package_dir={'': 'src'})

Article author: Andrei Olegovich