Create a simple Python package

To organize Python files in your project you can or better should place them in directories to better manage and find them.

Project setup

I've set up my sample class (dog.py) which looks like this:

class dog:
    '''class from https://docs.python.org/3/tutorial/classes.html'''
    def __init__(self, name):
        self.name = name
        self.tricks = []    # creates a new empty list for each dog

    def add_trick(self, trick):
        self.tricks.append(trick)

and my app.py file which looks like this:

import dog

dogInstance = dog.dog("Alfred")
dogInstance.add_trick("Trick1")

for dogTrick in dogInstance.tricks:
    print(dogTrick)

The whole folder has now 2 files.

Creating a package

Let's move our dog.py file to a new folder named animals, because later we possible add a cat or any other animal.

Now our linter&compiler tells us that he can't find the module dog.
To fix this we need to create an empty files named __init__.py in the animals folder.

Python will thread this folder as a package (cotainer for one or more modules) and the file dog.py as a module.
In file system terms this means:

  • package = folder
  • module = file

Fixing the import

Our code in app.py still doesn't work because the import is broken.
To fix this we need to change the import from import dog to import animals.dog, because the dog module is now in the animals package.

import animals.dog

dogInstance = animals.dog.dog("Alfred")
dogInstance.add_trick("Trick1")

for dogTrick in dogInstance.tricks:
    print(dogTrick)

import from

animals.dog.dog isn't very nice to write and doesn't look good.
To change this we can modify the import statement to this: from animals.dog import dog This tells python to only import the class dog from the module dog in package animals.
The app.py file now looks like this:

from animals.dog import dog

dogInstance = dog("Alfred")
dogInstance.add_trick("Trick1")

for dogTrick in dogInstance.tricks:
    print(dogTrick)

Very nice! What do you think?


comments powered by Disqus