Package your Python code as Wheel File (Part-20)

Posted by

Package your Python code as Wheel File

If you want to share code with others or create libraries for your code so other can use your code. It can done by converting your code to .whl file.

PIP is python package manager , that use to install python package

Prerequisites

  1. Python and pip installed: Ensure you have Python and pip installed on your system.
  2. Setuptools and wheel packages: Install the setuptools and wheel packages if you haven’t already. You can install them using pip:

Install setuptools and wheel

pip install setuptools wheel

Install wheel

Steps for Packaging your Python Code as a .whl File

  1. Create your project structure: Organize your project directory as follows:

__init__.py

The __init__.py file can be empty, but it should be present in the directory.

setup.py

Create a setup.py file in the root directory of your project (one level above your module folder). Below is an example content for setup.py:

myproject/
    mypackage2/
        __init__.py
        calculations.py
    setup.py

Write your setup.py file: The setup.py file is used to specify the details of your package. Here is an example of what it might look like:

from setuptools import setup, find_packages

setup(
    name="mypackage2",
    version="0.1",
    packages=find_packages(),
    install_requires=[
        # List your project's dependencies here.
        # For example: 'requests',
    ],
    entry_points={
        'console_scripts': [
            # Add console scripts if you have any
            # For example: 'myscript = mymodule:main',
        ],
    },
    author="Your Name",
    author_email="your.email@example.com",
    description="A brief description of your module",
    long_description=open('README.md').read(),
    long_description_content_type='text/markdown',
    url="https://github.com/yourusername/mymodule",
    classifiers=[
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
    ],
    python_requires='>=3.6',
)

or setup file:

import setuptools

setuptools.setup(
    name="mypackage2",  # Replace with your package name
    version="0.0.1",
    author="Maheer",  # Replace with your name
    author_email="maheer3222@gmail.com",  # Replace with your email
    description="calculation package",  # Replace with your package description
    packages=setuptools.find_packages(),
    classifiers=[
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
    ],
    python_requires='>=3.6',
)

Note – in setup file name should be same as folder name in which __init__.py and code file in which actual code exist for eg calculations.py. For details please see below highlighted name = “mypackage2”

Generate the distribution archives: Run the following command in your project directory:

python setup.py sdist bdist_wheel

Use the .whl File for Installation

You can now use the .whl file from the dist folder for installations. The command to install the package using the .whl file is:

pip install path/to/yourpackage.whl

pip install dist\mypackage2-0.0.1-py3-none-any.whl

Upload your package to PyPI (optional):

If you want to share your package on PyPI, you need to install twine:\

pip install twine

Then, upload your package using:

twine upload dist/*

By following these steps, you will have packaged your Python code into a .whl file, which can be easily installed and distributed.

Step-by-Step Guide

Step 1: Set Up Your Project Directory

Create Project Directory: Create a directory for your project and navigate into it.

    mkdir my_project
    cd my_project
    

    Create a Python Package: Inside your project directory, create a directory for your package.

    mkdir my_package
    touch my_package/__init__.py
    

    Add Your Python Code: Add your Python modules to the my_package directory. For example, create a simple module:

    def addition(x,y):
        return x+y
    
    def substract(x,y):
        return x-y
    
    def multiple(x,y):
        return x*y

    Step 2: Create a Setup Script

    1. Create setup.py: Create a setup.py file in the root of your project directory. This file is used to specify the metadata and options for your package.
    import setuptools
    
    setuptools.setup(
        name="mypackage",  # Replace with your package name
        version="0.0.1",
        author="Patrick",  # Replace with your name
        author_email="Patrick3222@gmail.com",  # Replace with your email
        description="calculation package",  # Replace with your package description
        packages=setuptools.find_packages(),
        classifiers=[
            "Programming Language :: Python :: 3",
            "License :: OSI Approved :: MIT License",
            "Operating System :: OS Independent",
        ],
        python_requires='>=3.6',
    )
    

    Step 3: Install Required Tools

    1. Install setuptools and wheel: Ensure you have setuptools and wheel installed in your environment.
    pip install setuptools wheel
    


    Packaging your Python code as a Wheel file is a common way to distribute your Python projects. Wheel is a built-package format for Python that allows for faster installation compared to source distributions. Here’s a step-by-step guide to create a Wheel file for your Python project.

    Step-by-Step Guide

    Step 1: Set Up Your Project Directory

    1. Create Project Directory: Create a directory for your project and navigate into it.shCopy codemkdir my_project cd my_project
    2. Create a Python Package: Inside your project directory, create a directory for your package.shCopy codemkdir my_package touch my_package/__init__.py
    3. Add Your Python Code: Add your Python modules to the my_package directory. For example, create a simple module:shCopy codeecho 'def hello(): print("Hello, World!")' > my_package/hello.py

    Step 2: Create a Setup Script

    1. Create setup.py: Create a setup.py file in the root of your project directory. This file is used to specify the metadata and options for your package.pythonCopy codefrom setuptools import setup, find_packages setup( name="my_package", version="0.1", packages=find_packages(), install_requires=[ # Add your project's dependencies here # e.g., 'requests', 'numpy' ], entry_points={ 'console_scripts': [ 'hello-world=my_package.hello:hello', ], }, )

    Step 3: Install Required Tools

    1. Install setuptools and wheel: Ensure you have setuptools and wheel installed in your environment.shCopy codepip install setuptools wheel

    Step 4: Build the Wheel File

    1. Build the Wheel: Use setup.py to build the wheel file.
    python setup.py bdist_wheel
    

    This command will create a dist directory containing the Wheel file, something like my_package-0.1-py3-none-any.whl.

    Step 5: Install the Wheel File

    1. Install the Wheel: You can now install your package using the Wheel file.
    pip install dist/my_package-0.1-py3-none-any.whl
    

    Step 6: Verify Installation

    1. Verify the Installation:

    Try to run below addition calculation from some other demo.py file

    from mypackage2 import calculations
    print(calculations.addition(1,5))
    
    output : 6

    Why Use __init__.py?

    1. Package Initialization:
      • The presence of an __init__.py file indicates to Python that the directory should be treated as a package. Without this file, the directory is not recognized as a package, and you cannot import modules from it.
    2. Package Initialization Code:
      • You can include initialization code in __init__.py that runs when the package is imported. This can be useful for setting up package-wide variables, importing submodules, or performing other initialization tasks.
    3. Control Over Imports:
      • __init__.py allows you to control what is available when the package is imported. You can define what gets imported when a user imports the package using from package import *.

    Roles of __init__.py

    1. Marking a Directory as a Package:
      • The primary role of __init__.py is to make Python treat the directory as a package.
    2. Package Initialization Code:
      • You can put initialization code here. For example, you might set up a logger or load configuration settings.
    3. Controlling Package Imports:
      • You can specify which submodules or functions should be accessible when the package is imported.

    Examples

    Example 1: Basic __init__.py

    # my_package/__init__.py
    print("Initializing the package")
    
    # You can import modules here to make them available at the package level
    from . import module1
    from . import module2
    

    Example 2: Defining Public Interface

    # my_package/__init__.py
    
    __all__ = ['module1', 'module2']
    
    # You can also include functions, classes, or variables
    def initialize():
        print("Package initialized")
    

    By defining __all__, you control what is imported with from my_package import *.

    Example 3: Initializing Package State

    # my_package/__init__.py
    
    # Import necessary submodules
    from .module1 import some_function
    from .module2 import some_class
    
    # Initialization code
    print("my_package is being initialized")
    
    # Define package-level variables
    config = {
        'setting1': True,
        'setting2': 'default'
    }
    
    # Package-level functions
    def initialize():
        print("Initializing package with settings:", config)
    

    Usage Examples

    Directory Structure

    my_project/
    ├── my_package/
    │   ├── __init__.py
    │   ├── module1.py
    │   └── module2.py
    └── main.py
    

    module1.py:

    # my_package/module1.py
    
    def some_function():
        print("Function in module1")
    

    module2.py:

    # my_package/module2.py
    
    class SomeClass:
        def __init__(self):
            print("Class in module2")
    

    main.py:

    # main.py
    
    import my_package
    
    my_package.initialize()
    my_package.module1.some_function()
    obj = my_package.module2.SomeClass()
    

    Running the Code

    When you run main.py, you should see output indicating that the package and modules are initialized correctly:

    Initializing the package
    my_package is being initialized
    Initializing package with settings: {'setting1': True, 'setting2': 'default'}
    Function in module1
    Class in module2
    

    Summary

    The __init__.py file is essential for:

    • Indicating that a directory is a Python package.
    • Running package initialization code.
    • Controlling the imports and public interface of the package.
    guest
    0 Comments
    Inline Feedbacks
    View all comments
    0
    Would love your thoughts, please comment.x
    ()
    x