Archive for the 'python' Category

Python modules, packages and code organization tips

I am learning Python programming.

Having programmed in Java and C# (CSharp) for a while, one of my first questions was how do I structure code in Python.

Java has namespaces and a class per file construct to organize code. C# (CSharp) has namespaces to organize code. I was looking for something similar in Python.

It seems the answer is Python code can be organized into modules and module namespaces can be organized using packages.

Packages translate to a folder in the file system.

main.py
music/
songs.py

A class called Song in songs.py can be imported into another module using the statement

from music.songs import Song

I was getting a python module not found or class not found error even though I had the right package folder structure.

On reading the python manual closely I realized that you need to create a __init__.py file in the package folder.

The folder now looks like,

main.py
music/
__init__.py
songs.py

After creating an empty __init__.py file in the package folder, I was able to import the Song class from music.songs module without any errors.

Some more tips on Python code organization.