How to write python __init__.py file for module

Question:

If I have a module folder structure like this:

studio
    tools
        __init__.py
        camera
            __init__.py
            camera.py
        element
            __init__.py
            element.py

How do I write the __init__.py files to make it so I can write my import statements like the following? There is a class object in the camera module called CameraNode that I would like to call like shown in the sample below.

from studio import tools
    
tools.camera.fn()
tools.CameraNode('')
tools.element.fn()
Asked By: JokerMartini

||

Answers:

If you have a studio/tools/__init__.py file like this:

from .camera import *
from .element import *

Then you can do a single import elsewhere like:

from studio import tools

and then reference everything as if it were directly in studio.tools.

Not sure if this is answering your question exactly, but hopefully it gets you going in the right direction.

Answered By: dkamins

An __init__.py file allows you to treat any directory as a Python package. It is not necessary to write anything in the file itself, just creating it in your directory is enough.

So camera, element, and tools can behave as packages.

However, if you want to access Python files in sub-directories as well, then you must import those in the __init__.py of the parent directory.

For example, if you want to do tools.camera then you must import camera in the __init__.py in the tools directory.

Otherwise, you will have to import camera separately to access all of the functions in it.

Answered By: pykam
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.