PHP To Python: Namespaces

In PHP, namespaces can be explicitly declared for each class. Generally we match namespaces to a folder structure. While in PHP, matching namespaces to a folder structure isn’t a language requirement, it’s strongly recommended that your software follows this standard to help future you and others maintain code you’re writing later down the line.

Python doesn’t give developers a chance to get this wrong. In Python namespaces are pre-defined by the language based on the module and package name.

Here’s my project structure:

project root
|
|- Animal
|- Dog
|- DogPack
|- tests
|- Animal
|- Dog

I have a package called ‘Animal’, which contains a module called ‘Dog’. Dog contains a class called ‘Fetch’ and fetch has a mathod: ‘run’. This gives us our namespace for the fetch class: Animal.Dog.Fetch.

To make use of this namespace and import this into our Dog module test:

from Animal.Dog import Fetch

fetch = Fetch()
fetch.run()

From inside the Animal package, we don’t need to refer to the package, just the module and class. From DogPack, we can run the fetch method just by importing the module and class with the following:

from Dog import Fetch

fetch = Fetch()
fetch.run()

Leave a Reply

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