PHP To Python: Modules and Packages

In Python we have a few ways to organise code that will be quite different from what you’re used to in PHP. First, I’m going to go through modules. Modules are .py files that contain classes, functions and variables. We can then consume these exposed elements by importing modules into our Python code:

Dog.py

class Dog:
    def get_breed(self, name):
    
        breed = "Unknown"

        if name == "Kevin":
            breed = "Labrador"

        return breed

Here our module contains a class. We can access the class by using the from keyword to reference the module name (Dog from Dog.py) and the class name from that module (Dog).

DogService.py

from Dog import Dog 

class DogService:
    def get_dog_info(self):
        name = "Kevin"

        dog = Dog()
        print("My dog's name is " + name)
        print(name + " is a " + dog.get_breed(name))

One major difference between PHP and Python is the PHP standard for one class per file. In Python this isn’t necessarily the case. Similar classes and functions should be grouped together in the same module. A good indication of this is when you notice several classes using the same dependencies, classes that do similar things, or classes that work together as a discrete set. It’s also perfectly acceptable to have a single class in a module if there is no related functionality to go with it.

It doesn’t just have to be related classes that live in a single module either, you could have a function or variable shared over multiple classes that doesn’t need to belong to a class because it’s on it’s own.

A package is essentially a directory of modules and it gives us another level of organisation in our codebase. A single package will contain multiple modules working together for a purpose, in the same way you might group multiple classes with a sub directory in a PHP project.

In order to turn a directory contaning Python code into a package, all we need to do is create a file called __init__.py in a directory containing Python modules.

If I was to put my Dog module from above into it’s own sub directory in my root directory, I would need to separate it out into it’s own package in order to access it from another directory on the same level.

project root
|– Dog/
|– tests/

To put this into a practical example, see the file structure above. Any code residing in the Dog/ folder would not be accessible to the tests/ folder until I turn the Dog/ directory into a Python package.

Leave a Reply

Your email address will not be published. Required fields are marked *