Categories
Programming python Technology Web Development

Python modules, packages and code organization tips

…it is important to have a __init__.py in the package folder.

Java has namespaces and a class per file construct to organize code.

C# (CSharp) has namespaces to organize code.

When I started to code in Python I was looking for a way to organize and structure code.

Python code can be organized into modules and 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.

Leave a Reply

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