Python create a package

Python create a package

Topics we discuss here

  • Why we need a package ?

  • How to create a package?

Package?

Consider you have a bunch of files which is having the common functionality or logic implemented in it , when we want to use it in our existing code either we need to point out the folder by sys.path.append or we need to copy the whole files into current directory

sys.path.append("path of common files ")

For avoiding this we need package

How to create a package?

Here We need to follow a structure, if a folder contains a dunder init we call it as a package in the same we need to directories and a setup.py and remaining other common py files

package_directory(article)
   | package(article)
        | __init__.py
        | pipeline_selector.py
        | executor.py
        | submodule(constants)
              | key_constants.py
   | README.md
   | setup.py
# pipeline_selector.py

def pipelines(details):
    print(details)
#executor.py
from article.pipline_selector import pipeline

def execute():
    pipeline("i am from executor")

When ever we import a function inside other file please use relative import like above

setup.py example structure

import setuptools
from setuptools import find_packages
from os import path

with open("README.md", "r") as fh:
    long_description = fh.read()


setuptools.setup(
    name="article",  # Replace with your own username
    version="0.0.1",
    author="Venkatesh",
    author_email="email.com",
    description="example lib",
    long_description=long_description,
    long_description_content_type="text/markdown",
    url="#",
    packages=setuptools.find_packages(),
    classifiers=[
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
    ],
    install_requires=[
          'pandas', # it will install required packages which are used inside the programming
          'xlrd',
          'numpy',
          'pymongo',
          'pypyodbc',
          'pymysql',
          'boto3'
      ],
    python_requires='>=3.6',
)

command

# go to the directory where setup.py present and execute
python3 setup.py install

After installation we can use this package anywhere we need like

from article import executor
executor.execute()

Thanks ..