April 28, 2019

Creating a Python Package that Prints Hello World

Welcome, fellow Python enthusiasts! In this blog post, we'll embark on a journey to create a simple Python package that does the timeless task of printing "Hello, World!" to the console. This may seem like a trivial exercise, but it serves as a fantastic introduction to the world of packaging and distributing Python code.

Step 1: Project Structure

First things first, let's set up the project structure. Create a new directory for your project, and inside it, create the following files:

hello_world_package/
|-- hello_world/
|   |-- __init__.py
|   |-- hello.py
|-- setup.py
|-- README.md

- hello_world is our package directory.
- **init**.py is an empty file that indicates the directory should be treated as a Python package.
- hello.py will contain the actual code to print "Hello, World!".
- setup.py is where we define package metadata and dependencies.
- README.md is a good practice to provide documentation for your package.

Step 2: Writing the Code

Now, let's write the code. Open hello_world/hello.py and add the following:

def print_hello():
    print("Hello, World!")

Simple, right? Our package will consist of this one function that prints our greeting.

Step 3: Define Package Metadata

Next, open setup.py and define the package metadata. This file informs Python's packaging tools about your package and how to install it. Here's a basic example:

from setuptools import setup, find_packages

setup(
    name='hello-world-package',
    version='0.1.0',
    packages=find_packages(),
    install_requires=[
        # If your package has any dependencies, list them here.
    ],
)

Replace # If your package has any dependencies, list them here. with actual dependencies if your package has any.

Step 4: Install and Test

Now, it's time to install our package locally. Open a terminal, navigate to your project directory, and run:

pip install .

This command installs the package in editable mode, allowing you to make changes and see the effects immediately.

Now, open a Python script or an interactive Python shell and try the following:

from hello_world import hello

hello.print_hello()

You should see "Hello, World!" printed to the console.

Step 5: Distribute Your Package

To share your package with the world, you can publish it on the Python Package Index PyPI. Before that, make sure to create an account on PyPI.

Once you have an account, you can use the following commands to upload your package:

pip install twine
python setup.py sdist bdist_wheel
twine upload dist/*

Congratulations! You've just created and shared your first Python package that prints "Hello, World!" to the world. This simple example lays the foundation for more complex and useful packages in the future. Happy coding!